Animate div with jQuery and set limits

I am trying to make a scrollable container using external buttons without using a plugin. I have a container named #feed with a fixed width and height and hidden overflow. Inside I have # feed-inner, which has a height of 560px. There are up and down arrows that move # feed-inner up and down, but I need to limit the animation so that # feed-inner cannot be moved to 0 or maximum height (560px).

$('#arrow-next').click(function() { $('#feed-inner').animate({ top: '-=70' }, 500, function() { }); }); $('#arrow-prev').click(function() { $('#feed-inner').animate({ top: '+=70' }, 500, function() { }); }); 
+4
source share
2 answers

You can get the value of the current position #feed-inner relative to #feed using $. position . With this, you can check if the position is at 0 or the maximum height is 560 pixels. The code will look something like this:

 $('#arrow-next').click(function() { $('#feed-inner').animate({ top: parseInt($('#feed-inner').position().top) == 0 ? '0' : '-=70' }, 500, function() { }); }); $('#arrow-prev').click(function() { $('#feed-inner').animate({ top: parseInt($('#feed-inner').position().top) == 560 ? '560' : '+=70' }, 500, function() { }); }); 

Note that #arrow-next will bring #feed-inner up (making it look like scrolling content down), which seems to contradict the β€œnext” label and vice versa for #arrow-prev .

One more note: when the #feed-inner position reaches 560px , there will be an empty canvas, since the element has completely moved to the bottom, and what you see is an empty #feed container. To avoid this, you would like to calculate the height of the #feed container and make sure that #feed-inner does not move after 560 - $(#feed).outerHeight();

+2
source

Looks like you just need some conditional statements in your click functions, no?

 if($('#feed-inner').position().top >= 70){ 

It will check if the top distance is greater than or equal to 70.

I do not know if your maximum height value is dynamic.

 if($('#feed-inner').position().top <= $('#feed-inner').css('maxHeight').split('px')[0]){ 

It will check if the top distance is less than the maximum value.

Unfortunately, maxHeight is not available as a raw integer, so we need to split the string into px and grab the first set of the array to get the raw integer.

0
source

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


All Articles