I'm currently trying to loop through sibling elements but can't get the loop to go back to the first sibling.
I'm using the nextOrFirst function as seen here
I've replicated what i'm trying to achieve in this fiddle
HTML
<div id="stories">
<div class="swapper"><p>number 1</p></div>
<div class="swapper"><p>number 2</p></div>
<div class="swapper"><p>number 3</p></div>
</div>
Javascript
$(document).ready(function() {
$.fn.nextOrFirst = function(selector) {
var next = this.next(selector);
return (next.length) ? next : this.prevAll(selector).last();
};
setInterval(
function swap() {
$(".swapper").each(function() {
var nextItem = $(this).nextOrFirst();
$(this).html($(nextItem).html());
return;
});
}, 5000);
});
Why not just move last element to the top and than remove last one
setInterval(
function swap() {
var $container = $("#stories");
$container.prepend($container.find('.swapper:last').html());// move last to top
$container.find('.swapper:last').remove(); // remove last
}, 2000);
I guess you trying to reach something like this: jsfiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With