giovaZ
giovaZ

Reputation: 1470

jQuery: select elements with slice

in a page i've got different divs elements with the same class

<div id="masterdiv">
  <div class="a"></div>
  <div class="a"></div>
  <div class="a"></div>
  <div class="a"></div>
  <div class="a"></div>
  <div class="a"></div>
  <div class="a"></div>
  <div class="a"></div>
  <div class="a"></div>
  <div class="a"></div>
<div>

with a setTimeout i want to take three elements for time do some action with them.

i tried with the slice function:

var elements = $("#masterdiv").find('.a');

var t = setInterval(function () {
   var currentElements = elements.slice(points.f, points.l); 
  /* where points.f = 0 and points.l = 3 */
  /* do something with currentElements then increment points.f and points.l +1 */

}, xinterval );

But there's a problem, at a certain time my code will reach a .slice(8,10) / .slice(9,11) and a in a selection of 11 divs.

So in these cases (point.l > elements.length()) i want select the first divs instead of the exceeded ones:

How can i accomplish this? Can i do it with slice or should i use another function?

Thanks in advance for all the help.

Upvotes: 0

Views: 860

Answers (2)

ricky
ricky

Reputation: 1684

you can increment your variable like this,

var elements = $("#masterdiv").find('.a');

  /* where points.f = 0 and points.l = 3 */
var t = setInterval(function () {
 var currentElements;
  
  if(points.l > elements.length && points.f<=elements.length){
    tempArr1 = elements.slice(points.f);
    tempVar = points.l % elements.length;
    tempArr2 = elements.slice(0,tempVar);
    currentElements = [...tempArr1,...tempArr2];
    
  }
  else{
   currentElements = elements.slice(points.f, points.l); 
  }
  
  /* do something with currentElements then increment points.f and points.l +1 */  

}, xinterval );

I have not covered edge cases,please find yourself ;)

Upvotes: 2

Kostas Minaidis
Kostas Minaidis

Reputation: 5516

An alternative, would be to use the pop() and push() array functions like this:

var $elements = $("#masterdiv").find('.a');
// Convert to native Array
var elements = Array.prototype.slice.apply($elements);

var t = setInterval(function () {

  elements.slice(points.f,points.l).forEach(function(el){ 

      // do something on the element... 
      $(el).addClass('debug');

   });
  elements.push(elements.shift()); // Re-arrange elements array for loop

}, xinterval );

Here's the codepen demo: http://codepen.io/kostasx/pen/mRVzqQ?editors=0010

Upvotes: 2

Related Questions