4

I'm looking for a javascript only solution to detect when my window has scrolled up past a certain element (like a div) and then trigger an event. In particular I need to show a navbar once I've scrolled past this element.

I can't use Jquery or other libraries. Plain JS.

Thanks!

kevinkt
  • 735
  • 12
  • 24

1 Answers1

9

Here is a JSFiddle Demo

You need to select the element that you want as the target.

var someElement = document.querySelector('whatever');

Then you need set an scroll event listener on the window object itself, which fires every time the user scrolls, then simply run a if statment to check if the element from the top of the screen is greater or equal to 0, if true run the following block of code.

window.onscroll = function(){
    //TOP
    if(someElement.getBoundingClientRect().top <= 0){
        console.log("TRIGGER: top of div reached.");
    }
    //BOTTOM
    if(someElement.getBoundingClientRect().bottom <= 0){
        console.log("TRIGGER: bottom of div reached.");
    }
}
  • Nice! This is exactly what I need. I also updated the fiddle with how I'd implement a fixed navbar. – kevinkt Nov 03 '16 at 21:54