Ad

Show Div After Scrolled Back To The Top

- 1 answer

I want to show a Top-Bar, when the user scrolled back to top of the site.

So e.g. the user scrolls down for a minimum of a 300-400px and then when he scrolls back up again to maybe around 100px (left to the top of the site) the bar should toggle / show up.

Thanks for your help! :)

Ad

Answer

You can add an event listener to document to check when a user scrolls down the page. Once they hit a preset breakpoint, you can remove a hidden class from your navbar element, like so:

var breakpoint = 400;
var navbar = $('.nav-bar');
$(document).scroll(function(){
    if($(this).scrollTop() >= breakpoint) {
        navbar.removeClass('hidden', 500);
    }
});

If your navbar is fixed, you can also check a boolean variable to see if the user has scrolled past the breakpoint, and then set it to true. If they scroll up past the breakpoint, you can then show the navbar, like so:

var breakpoint = 400;
var scrolledPastBreakpoint = false;
var navbar = $('.nav-bar');
$(document).scroll(function(){
    if($(this).scrollTop() >= breakpoint) {
        scrolledPastBreakpoint = true;
    };
    if($(this).scrollTop() < breakpoint && scrolledPastBreakpoint) {
        navbar.removeClass('hidden', 500);
    };
});
Ad
source: stackoverflow.com
Ad