Home > Net >  How to apply CSS styles based on existence of Browser API feature?
How to apply CSS styles based on existence of Browser API feature?

Time:05-16

I have a page which has the content invisible (opacity = 0) and based on the isIntersecting property as the user scrolls down the opacity changes to 1. It's pretty simple and a basic implementation of the IntersectionObserver API.

However I was having some issue with Safari support and maybe there are others like me who are using older browsers. So I used feature detection in the JS file as below

if ("IntersectionObserver" in window){
    
    // Javascript here
}

And this works fine for the browsers where it was working even earlier. However my CSS still has the opacity as 0 and I need to show that content with opacity as 1 to those browsers who don't support IntersectionObserver..

How do I do this?

In other words, is there a way where I can apply conditions in CSS and even if there is, then how do I take a JS variable into CSS?

Any advise would be appreciated.

CodePudding user response:

Intersection Observer isn't supported below iOS 12, so for the older versions you can use https://www.npmjs.com/package/intersection-observer, and then no need for additional CSS changing or anything.

CodePudding user response:

You could set the opacity using a CSS variable and change that in the JS.

if ("IntersectionObserver" in window){
    
    // Javascript here
}
else {
  document.querySelector('.content').style.setProperty('--opacity', 1);
}
.content {
  --opacity: 0;
  opacity: var(--opacity);
}
<div >some content</div>

  • Related