Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide div when scrolling down and then show it as you scroll up?

Tags:

jquery

Okay bear with me, I know this might have been asked a few times but I can't get the exact answer after searching a bit.

Basically what I want is as the user starts to scroll down, after a certain height the div disappears.. and it remains disappeared until the user starts to scroll up. Right when the user starts to scroll up, the div appears again. I need some sort of fade effects for this as well.

This is what I've come up with by looking at other answers so far. With this, the div does disappear after a certain height as you scroll down, but it only re-appears when you reach that same height when you scroll up. I want the div to immediately show itself when the user starts to scroll up. This code doesn't have any animations either...

jQuery(window).scroll(function() {

    if (jQuery(this).scrollTop()>0)
     {
      jQuery('.myDIV').fadeOut();  
     }
    else
     {
      jQuery('.myDIV').fadeIn();
     }
 });
like image 735
Maaz Avatar asked Jul 28 '13 13:07

Maaz


1 Answers

I'm not the greatest JQuery-artist either, but I think this should work:

var mywindow = $(window);
var mypos = mywindow.scrollTop();
mywindow.scroll(function() {
    if(mywindow.scrollTop() > mypos)
    {
        $('.myDIV').fadeOut();  
    }
    else
    {
        $('.myDIV').fadeIn();
    }
    mypos = mywindow.scrollTop();
 });

You can see mypos is updated every time the user scrolls, up or down.

Edit

I've made some updates upon your request in a fiddle: http://jsfiddle.net/GM46N/2/. You can see in the js-part of the fiddle that I've made two options - one is with .fadeIn() and .fadeOut() (this time working - on your site the code I provided is not running), the second one is using .slideToggle().

Here's the updated js:

var mywindow = $(window);
var mypos = mywindow.scrollTop();
var up = false;
var newscroll;
mywindow.scroll(function () {
    newscroll = mywindow.scrollTop();
    if (newscroll > mypos && !up) {
        $('.header').stop().slideToggle();
        up = !up;
        console.log(up);
    } else if(newscroll < mypos && up) {
        $('.header').stop().slideToggle();
        up = !up;
    }
    mypos = newscroll;
});

I've also added an extra variable, up, to only fire the events when the user scrolls up the first time and the next time the toggle gets fired is when he scrolls down and so on. Otherwise the events are fired maaaaany times (you can test it by using the previous code with .slideToggle() to see the massive amount of event-firing).

re-edit: I've also added .stop(), so now if there is still an effect running that effect gets stopped first, to prevent lag if a user quickly scrolls up&down.

like image 124
jdepypere Avatar answered Oct 20 '22 17:10

jdepypere