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.
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/
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.
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