Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a circular next() on jquery?

Tags:

jquery

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.

like image 497
markzzz Avatar asked Dec 12 '22 13:12

markzzz


2 Answers

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/

like image 82
Karl-André Gagnon Avatar answered Jan 11 '23 22:01

Karl-André Gagnon


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.

like image 20
Denys Séguret Avatar answered Jan 11 '23 23:01

Denys Séguret