Search code examples
jqueryscrollfadeinfadeout

jQuery - fadeOut on Scroll / fadeIn on "scrollstop"


I have a div positioning working which gets fired by the scroll-event. What happens it that the scroll event gets fired a bunch of times which results in a flickering div. My plan is to fade out that div and fade back in as soon as no more scroll event is fired. How can I check that scrolling is over? I thought about a combination of timeout <-> scroll but actually nothing worked as I hoped. Here's what i got so far.

$(document).ready(function(){

    //var animActive = false;

    $(window).scroll(function() {

        /*
        if (animActive == false){
            animActive = true;
            $('.mceExternalToolbar').fadeOut(100, function () {
                $('.mceExternalToolbar').fadeIn(3000, function () {
                    animActive = false;
                    console.log("NOW");
                });
            });
        }
        */

        topParentx = $('#tinyMCEwrapper').position().top;
        if ($(this).scrollTop() >= topParentx){
            $('.mceExternalToolbar').css('top', ($(this).scrollTop()-topParentx) + "px");
        } else {
            $('.mceExternalToolbar').css('top', "0px");
        };
    });

});

As you can see I left one of my last attempts in there, but the callbacks of the fade-function didn't work as expected.


Solution

  • Unfortunately there is no concept of scroll-stop so you can't really trigger an animation from that. What may work better is to instead animate the 'top' property of your div so that it smoothly slides to it's new position instead of flickering.

            topParentx = $('#tinyMCEwrapper').position().top;
            var topTarget = "0px";
            if ($(this).scrollTop() >= topParentx){
                topTarget = ($(this).scrollTop()-topParentx) + "px";
            }
            $('.mceExternalToolbar').stop().animate({top, topTarget}, 500);