Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
77
rated 0 times [  81] [ 4]  / answers: 1 / hits: 24683  / 14 Years ago, wed, january 26, 2011, 12:00:00

I have an array of HTML elements. I'm checking whether a previous object in the array exists like this:



var boxes = $('.box'); // creating the array

boxes.each(function(i){ // going through the array
var prevBox = i>0?$(boxes[i-1]):false; // check whether a previous box exists
if (prevBox) { } // do something
else { } // do something else
});


This works well. But I would also need to check the existence of every fourth object (box) in the array, or more precisely whether an object three objects before the current one exists.



This doesn't work:



var prevBox = i>0?$(boxes[i-4]):false;


I believe using jQuery.grep() and checking if (i % 4) == 0 might be the answer, but with my limited knowledge of Javascript, I don't know how to apply it to what I have now.



Anyone can help? Thanks!


More From » jquery

 Answers
31

You can use the modulus operator in the loop to see if you are on a fourth interval.



Question was clarified.



var boxes = $('.box'); // creating the array

boxes.each(function(i){
if( i >= 3 ) {
var prevBox = boxes.eq( i - 3 );
var pos = prevBox.position();
var top = pos.top;
}
});

[#94043] Tuesday, January 25, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jonmicahm

Total Points: 603
Total Questions: 120
Total Answers: 108

Location: Guam
Member since Fri, Jul 31, 2020
4 Years ago
;