-1

ive wrote a simple script that isnt working as intentioned:

var prevscroll = 0;
$(document).scroll(function(){

    var currscroll = $(document).scrollTop();
    if(currscroll > prevscroll){
        $("header").toggle();
        prevscroll = currscroll;
    }
    if(currscroll < prevscroll){
        $("header").toggle();
        prevscroll = currscroll;
    }
});

When the page is scrolled down, its meant to hide the header and only show it if its scrolled up however whats happening is as i scroll down its flicking on and off. :|

I think I may of just spotted a silly error! ofcourse its going to keep flickering since prev scroll keeps increasing.

1
  • 1
    every time that condition returns true you are toggling the appearance causing it to flash. You need to specify either hide() or show() depending on if you are scrolling up or down. Commented Jan 20, 2014 at 23:17

1 Answer 1

2

You can't use toggle() the way you are because the scroll event is called many, many times so if it's called more than once with the same value for your if statement, then it will flicker on, then off, then on, then off each time you call .toggle(). You need to explicitly hide or show when your condition is met.

I don't quite follow exactly what you're trying to do with prevscroll, but perhaps this is what you want:

var prevscroll = 0;
$(document).scroll(function(){

    var currscroll = $(document).scrollTop();
    if(currscroll > prevscroll){
        $("header").hide();
        prevscroll = currscroll;
    }
    if(currscroll < prevscroll){
        $("header").show();
        prevscroll = currscroll;
    }
});

This will hide the header anytime you are scrolling down further and show the header as soon as you start to scroll up.

Sign up to request clarification or add additional context in comments.

2 Comments

Doh, I kind of caught on after I posted! Thanks for answering
Im using prevscroll to test which direction is being scrolled to hide nav bar on mobiles when scrolling down, but then showing when scrolling up instead of having a static bar right at the top. (if that made sense)

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.