Override scroll up/down function if scrollTop is equal to 0

1k views Asked by At

I am having some trouble with this one. I have a transparent header that fades out as the user scrolls down the page. As the user scrolls up, the header has a black background to emphasize its existence. Everything is working fine, but I need to override everything that happens in the function if and only if the scrollTop is equal to 0. So when the user scrolls all the way back to the top, the header returns to transparent. My current code is:

   $(window).scroll(
        {
            previousTop: 0
        }, 
        function () {
        var currentTop = $(window).scrollTop();
        if (currentTop < this.previousTop ) {
            header.fadeIn('slow');
            header.css('background', 'rgba(0,0,0,.9)');
        } else {
            header.fadeOut();
        }
        this.previousTop = currentTop;
    });

Any help is much appreciated!

1

There are 1 answers

0
Ucinorn On BEST ANSWER

Here you go: just add a catch for when the scrollTop value is 0.

  $(window).scroll(
        {
            previousTop: 0
        }, 
        function () {
        var currentTop = $(window).scrollTop();
        if (currentTop < this.previousTop ) {
            if (currentTop != 0 ) { // new if statement here prevents fadein if at top of page
               header.fadeIn('slow');
               header.css('background', 'rgba(0,0,0,.9)');
            }
        } else {
            header.fadeOut();
        }
        this.previousTop = currentTop;
    });