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!

5

1 Answer 1

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.");
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Nice! This is exactly what I need. I also updated the fiddle with how I'd implement a fixed navbar.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.