Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery next loop not going back to first child

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);

});
like image 524
user3177414 Avatar asked Jul 09 '14 10:07

user3177414


1 Answers

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

like image 174
Nikita Holovach Avatar answered Oct 02 '22 22:10

Nikita Holovach