简体   繁体   中英

Animate element on user scroll

I am currently using the logic below to animate a navigation block. It is working well when user scroll greater than 5px, the element animates out of the viewport. However the user must scroll top top of window for the element to animate back into position.

Rather than waiting for the user to scroll to the top of page how do I trigger the animate function as soon as a user scrolls up? (Not waiting till they get to the top of page)

    var _throttleTimer = null;
    var _throttleDelay = 100;
    var $window = $(window);
    var $document = $(document);

    $document.ready(function () {

        $window
            .off('scroll', ScrollHandler)
            .on('scroll', ScrollHandler);

    });

    function ScrollHandler(e) {
        clearTimeout(_throttleTimer);
        _throttleTimer = setTimeout(function () {
            //console.log('scroll');

            if($(window).scrollTop() > 5) {
                $( ".mobile_header .content" ).animate({
                    top: "-34px"
                  }, 100 );
            } else {
                ////Need help here
                $( ".mobile_header .content" ).animate({
                    top: "34px"
                  }, 100 ); 
            }

    }, _throttleDelay);
}

Heres is the solution. had to modify logic to detect if the user scroll down or scroll up.

var _throttleTimer = null;
var _throttleDelay = 100;
var lastScrollTop = 0;
var $window = $(window);
var $document = $(document);

$document.ready(function () {
    $window
     .off('scroll', ScrollHandler)
     .on('scroll', ScrollHandler);
});

function ScrollHandler(e) { 
    clearTimeout(_throttleTimer); 
    _throttleTimer = setTimeout(function () { 
        console.log('scroll');

        var st = $(this).scrollTop(); 

        if (st > lastScrollTop && $(window).scrollTop() > 5){ 
            $( ".mobile_header .content" ).animate({ 
                top: "-34px" 
            }, 100 ); 
        } else { 
            $( ".mobile_header .content" ).animate({ 
                top: "34px" 
            }, 100 ); 
        } 

        lastScrollTop = st; 
    }, _throttleDelay); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM