1
2

Is there a circular next () in jquery?

This is my code:

<div class="container"> <div class="prova">1</div> <div class="prova">2</div> <div class="prova">3</div> </div> 

I want to get the contents of each div every 500 ms. When I get to the third position, return to the first and so on. Circular next() .

Tried using:

 var primoElem = $('.prova').first(); setInterval(function () { console.log(primoElem.html()); primoElem = primoElem.next(); }, 500); 

but I get only 3 results, then it stops.

+4
source share
5 answers

When the jQuery function does not work the way you want, you can always change it for your needs by saving the old function and overriding it. Or you can also create your own function if you do not want to change the behavior of jquery. As an example, to override, add this to your code after loading jquery:

 $.fn.oldNext = $.fn.next; $.fn.next = function(selector){ var selector = selector || ''; return this.oldNext(selector).length ? this.oldNext(selector) : this.siblings(selector).addBack(selector).first(); } 

Then your code will work.

If you do not want to override, just change the name:

 $.fn.loopNext = function(selector){ var selector = selector || ''; return this.next(selector).length ? this.next(selector) : this.siblings(selector).addBack(selector).first(); } 

Then name it like this:

 primoElem.loopNext(); 

Fiddle: http://jsfiddle.net/EcnSH/

+7
source

You could just do this:

 primoElem = primoElem.next(); if (!primoElem.length) primoElem = $('.prova').first(); 

Sometimes there is no standard function that does exactly what you want, but it doesnโ€™t matter if this only means that your specific need is covered by an additional line of code.

+5
source

Just run the check:

 setInterval(function () { console.log(primoElem.html()); primoElem = primoElem.next().length ? primoElem.next() : $('.prova').first(); }, 500); 
+1
source

You can also use a counter:

 var primoElemColl = $('.prova'), counter = 0; setInterval(function () { var primoElem = primoElemColl.eq(counter++ % primoElemColl.length); console.log(primoElem.html()); }, 500); 
0
source

At the beginning there is no "go first when finally", I tend to use indexes for this: here I add a class to the element, moving it back and forth to the beginning based on the index.

 var primoElem = $('.prova'); var provaIndex = 0; var provaLastIndex = primoElem.length - 1 primoElem.eq(provaIndex).addClass('showmyprogress'); setInterval(function () { $('.showmyprogress').removeClass('showmyprogress'); provaIndex = (provaIndex === provaLastIndex) ? 0 : provaIndex + 1; primoElem.eq(provaIndex).addClass('showmyprogress'); }, 500); 

show this in action: http://jsfiddle.net/wb9V3/

0
source

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


All Articles