Stop animation after scrolling to a specific point

I currently have this for images that move as they scroll around the screen (performed using jQuery), but I want them to stop at a specific point.

This is the code that 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" ); }); }); 
+4
source share
3 answers

If you just want to stop at a certain 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 ensures that it never passes 500 pixels from the top of the page.

+3
source

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 just use the class for all your sums, for example:

 var $bags = $(".bag"); 
+2
source

First summarize the calls with:

 $("#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

0
source

Source: https://habr.com/ru/post/1441130/


All Articles