How to animate elements in a container using jQuery?

I am working on an article carousel using jQuery to try to better strengthen the structure. I have a containing div, and in this div I have several articles.

<div id="container"> <article> <h3>Article Heading</h3> <p>Article Content</p> </article> <article> ... </div> 

Div is formatted as a specific width and height, and overflow is hidden

I try to animate it, so when the user clicks the button, it calls a function to scroll through the next or previous article

 var articles = -1; var currentPosition = -1; window.onload = function(){ articles = $("#container>article"); currentPosition = 0; } function scrollNext(){ $('#container').animate({ scrollTop: $(articles[currentPosition+1]).offset().top }, 750); currentPosition++; } 

However, when the scrollNext function is called, it will scroll to the paragraph of the next article or will fail.

I am wondering if this is a problem with the selector, or perhaps with my page style, or what would be the right way to do this. See full page here.

Or try it on jsfiddle

+4
source share
2 answers

Your margin is confused. Why not try something like this?

 var box = $("#container"), height = box.height(); currentPosition++; box.animate({scrollTop: currentPosition*height}); 
+2
source

You use .offset() , which gives you an offset compared to the body.

Since you want to scroll inside the div#container , you need to use .position()

http://api.jquery.com/position/

And using position() requires the div #container be position: relative; in your css.

Once you have this in your jQuery, you need to change the scrollTop animation to enable scrollTop() from the div#container added to position() next article

So:

 $('#container').animate({ scrollTop: $('#container').scrollTop() + $(pdiv).position().top }, 750); 

You can see how it all works in the updated jsfiddle:

http://jsfiddle.net/9ryjy/1/

+1
source

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


All Articles