user1763455
user1763455

Reputation: 43

Stopping an animation after scrolling to a certain point

I currently have it for images that move as you scroll down the screen (done with jQuery) but I want them to stop at a certain point.

This is the code i have at the moment.

$(document).ready(function() {
        var $bagSix = $("#six");
        var $bagEight = $("#eight");
        var $bagTen = $("#ten");
        var $bagTwelve = $("#twelve");

        $(window).scroll(function(){            
                $bagSix
                .stop()
                .animate({"marginTop": ($(window).scrollTop() + 30) + "px"}, "slow" );

        });

                $(window).scroll(function(){            
                $bagEight
                .stop()
                .animate({"marginTop": ($(window).scrollTop() + 30) + "px"}, "slow" );          
        });

                $(window).scroll(function(){            
                $bagTen
                .stop()
                .animate({"marginTop": ($(window).scrollTop() + 30) + "px"}, "slow" );          
        });

                $(window).scroll(function(){            
                $bagTwelve
                .stop()
                .animate({"marginTop": ($(window).scrollTop() + 30) + "px"}, "slow" );          
        });
    });

Upvotes: 4

Views: 1521

Answers (3)

tobspr
tobspr

Reputation: 8376

First, summarize the calls with the use of:

$("#image1, #image2, etc.")

Then edit your function:

$(window).scroll(function(){            
    
$images.stop().animate({
        "marginTop": Math.min($(window).scrollTop() + 30, <stopping point>) + "px"}, "slow" );   
 });  

     

Hope that helps

Upvotes: 0

Eric
Eric

Reputation: 3172

If you want to just stop at a specific point, you can do:

var new_top = Math.min($(window).scrollTop() + 30, 500);
$bagSix
.stop()
.animate({"marginTop": new_top + "px"}, "slow" );

This computes the new target location and makes sure it never passes 500 pixels from the top of the page.

Upvotes: 3

Roko C. Buljan
Roko C. Buljan

Reputation: 206669

jsBin demo

$(document).ready(function() {

    var $bags = $("#six, #eight, #ten, #tweleve");

    $(window).scroll(function(){
        var winScrT = $(window).scrollTop();
        if(winScrT < 789 ){           // or what you prefer         
            $bags.stop().animate({marginTop: winScrT+30 }, "slow" );
        }
    });

});

And why not to use just a class for all your bags like :

var $bags = $(".bag");

Upvotes: 2

Related Questions