0

What I Basically Want is to change the z-index ( Other CSS Property, EG: Color ) of a div when it's in the Viewport of the Viewer (Using JS, CSS or any other way).

<HTML>
   <head>

   </head>

   <body>
      <!--Something Here-->

      <div>Hello</div> <!--Initialy this is what is in the Viewport -->
      <div>You Are Here</div> <!--When this comes in to the Viewport z-index of this change to higher value-->
      <div>Bye</div> <!--when in to the Viewport z-index of this change to higher value-->
      
      <!--Something Here-->
   </body>
<HTML>

Is there a Way to Achieve This Without Calculating Positions of Elements?

DarkZeus
  • 61
  • 8

1 Answers1

1

IntersectionObserver will tell you whether an element is in view or not.

Here's a very simple example based on the code in the question. As an element comes into/out of view it has 'I am in/out of view' put as its innerHTML. Obviously change that for whatever restyling etc you want.

let callback = (entries, observer) => {
  entries.forEach(entry => {
  // from MDN:
    // Each entry describes an intersection change for one observed
    // target element:
    //   entry.boundingClientRect
    //   entry.intersectionRatio
    //   entry.intersectionRect
    //   entry.isIntersecting
    //   entry.rootBounds
    //   entry.target
    //   entry.time
    entry.target.innerHTML = entry.isIntersecting ? 'I am in view!' : 'I am not in view';
    //do whatever you want to do when the div goes out of or comes into the viewport
  });
};
const divs = document.querySelectorAll('div');
const observer = new IntersectionObserver(callback);
divs.forEach(div => {
  observer.observe(div);  
});
div {
height: 100vh;
}
div:nth-child(1) {
  background: linear-gradient(red, blue);
}
div:nth-child(2) {
  background: linear-gradient(lime, cyan);
}
div:nth-child(3) {
  background: linear-gradient(orange, purple);
}
      <!--Something Here-->

      <div>Hello</div> <!--Initialy this is what is in the Viewport -->
      <div>You Are Here</div> <!--When this comes in to the Viewport z-index of this change to higher value-->
      <div>Bye</div> <!--when in to the Viewport z-index of this change to higher value-->
      
      <!--Something Here-->
A Haworth
  • 30,908
  • 4
  • 11
  • 14