-1

Hello is it possible to rewrite the following JQuery snippet:

$(window).scroll(function (event) {
  var scroll = $(window).scrollTop();
    $(".navigation").toggleClass("is-active", scroll >= $("example-div").offset().top);
});
$(window).scroll(); 

Into vanilla JS? I've tried everything, and searched through some other questions, to no avail.

Thanks.

  • So `addEventListener("scroll", () => Array.from(document.querySelectorAll(".navigation")).forEach(({ classList }) => classList.toggle("is-active", scroll >= theOtherElement.getBoundingClientRect().top + pageYOffset))); dispatchEvent(new Event("scroll"));`, whatever `theOtherElement` is (`$("example-div")` implies an `` element). – Sebastian Simon Feb 10 '22 at 11:03

1 Answers1

2

You can use the Intersection Observer API like this :

const target = document.querySelector('#static');
const floating = document.querySelector('#floating');

const observer = new IntersectionObserver(
  ([entry]) => {
    if (entry.isIntersecting)
      floating.innerText = 'Red is visible'
    else
      floating.innerText = 'Red is invisible'
  }, {
    threshold: 0
  }
);

observer.observe(target)
body {
    margin: 0
}

main {
    height: 200vh;
}

#static {
    background-color: red;
}

#floating {
    position: fixed;
    left: 55px;
    background-color: yellow;
}

#static,
#floating {
    width: 50px;
    height: 50px;
}
<main>
  <div id="floating">
  </div>
  
  <div id="static">
  </div>    
</main>

compatibility link

Namysh
  • 3,717
  • 2
  • 9
  • 17