4

This 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 every 500ms the content of each div. When I reach the 3rd position, return to the first one, and so on. A circular next().

Tried with:

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

but I get only 3 results, then it stops.

j08691
  • 204,283
  • 31
  • 260
  • 272
markzzz
  • 47,390
  • 120
  • 299
  • 507

5 Answers5

7

When a jQuery function doesnt work as you want, you can always change it for your need by saving the old function and override it. Or you can also create your own function if you dont want to change jquery behavior. As example, for overiding, add this to your code after jquery load :

$.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 dont 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 call it like that :

primoElem.loopNext();

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

David Bell
  • 183
  • 1
  • 8
Karl-André Gagnon
  • 33,662
  • 5
  • 50
  • 75
5

You could simply do this :

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

Sometimes there is no standard function doing exactly what you want but it doesn't matter if it only means your very specific need is covered by an additional line of code.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
1

Just run a check:

setInterval(function () {
    console.log(primoElem.html());
    primoElem = primoElem.next().length ? primoElem.next() : $('.prova').first();
}, 500);
tymeJV
  • 103,943
  • 14
  • 161
  • 157
0

You could also use a counter:

var primoElemColl = $('.prova'),
    counter = 0;
setInterval(function () {
    var primoElem = primoElemColl.eq(counter++ % primoElemColl.length);
    console.log(primoElem.html());
}, 500);
sroes
  • 14,663
  • 1
  • 53
  • 72
0

There is no "go to first when at last" however, I tend to use indexes for this: Here I add a class to the element, moving it along and back to the top based on an 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 it in action: http://jsfiddle.net/wb9V3/

Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100