0
votes

I am trying to trigger an animation when the user scrolls down the page. So when he scrolls beyond a certain point, I want to have a div sliding in the webpage and I don't want it to slide away if the user scrolls up.

It works fine except that when I scroll up and down during the animation it delays it and the motion is not fluid at all.

I am using this javascript to trigger the animation:

    $(document).ready(function() { 
    jQuery(function($) {
        function fixDiv() {
            var $cacheLaptop = $('#red-div');
            var check=new Boolean();
            check=false;
            if ((check==false) && ($(window).scrollTop() > 500)) {  
                check=true;    
                $cacheLaptop.stop().animate(
                    { left: 0 }, {
                     duration: 1000,
                 });   
            }
        }
        $(window).scroll(fixDiv);
        fixDiv();
    });

}); 

I have created a jsfiddle so you can see my problem: http://jsfiddle.net/B4WEV/3/

Does anyone have an idea how to fix this?

Many thanks!

2

2 Answers

0
votes

I think this is more along the lines of what you're trying to do.

$(document).ready(function() { 
    function fixDiv() {
        var $cacheLaptop = $('#red-div');
        if (($(window).scrollTop() > 500)) {   
            $cacheLaptop.animate(
                { left: 0 }, {
                    duration: 1000,
                });   
            $cacheLaptop.off('scroll');
        }
    }
    $(window).scroll(fixDiv);
    fixDiv();
}); 

What happened with your code is that the fixDiv function is called everytime the user scrolls, and restarts the animation from the div's current position, with the duration of 1 second. This is obviously not what you intended, and you tried to mitigate that by checking if a flag had been set -- but you define the boolean in the scope of the handler function, and so it is redefined every time the handler is called (in this case, every time the user scrolls.)

Instead, the handler function is called when the user is scrolling, only animates when scrolling below the 500 pixel mark, and after doing so removes the scroll handler by calling $cacheLaptop.off('scroll');

Hope that helps.

0
votes

You should use this plugin: http://imakewebthings.com/jquery-waypoints/ to trigger the animation start, and then just let it play.