Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger event when scroll past bottom of element?

So on my website I have a static header at the very top of the site -- it's not fixed to the top of the viewport. However, what I'd like to do is once the user scrolls past the bottom of this div, for a fixed navbar to appear. My code almost works, but only triggers at the top offset of the div, which is the very top of the page. Here's my code:

$("#header-2").hide(); // hide the fixed navbar initially

var topofDiv = $("#header-container").offset().top; //gets offset of header
$(window).scroll(function(){
    if($(window).scrollTop() > topofDiv){
       $("#header-2").show();
    }
    else{
       $("#header-2").hide();
    }
});

Again, I need to trigger showing the fixed navbar once the user scrolls past the bottom of #header-container, not the top like it does now. Help?

like image 231
Tom Maxwell Avatar asked Dec 19 '13 04:12

Tom Maxwell


People also ask

How do I check if a div is scrolled to the bottom?

To detect when a user scrolls to bottom of div with React, we can check if the sum of the scrollTop and clientHeight properties of a scrollable element is equal to the scrollHeight property of the same element. We call the useRef hook to create a ref and we assign the returned ref to the inner div, which is scrollable.

What is $( window scrollTop ()?

jQuery scrollTop() Method The scrollTop() method sets or returns the vertical scrollbar position for the selected elements. Tip: When the scrollbar is on the top, the position is 0.


1 Answers

I think that if you add the height of the div to the top offset you'll get the behaviour you want

$("#header-2").hide(); // hide the fixed navbar initially

var topofDiv = $("#header-container").offset().top; //gets offset of header
var height = $("#header-container").outerHeight(); //gets height of header

$(window).scroll(function(){
    if($(window).scrollTop() > (topofDiv + height)){
       $("#header-2").show();
    }
    else{
       $("#header-2").hide();
    }
});
like image 78
Leo Avatar answered Oct 09 '22 22:10

Leo