I am trying to loop through a series of elements, iterating a number and applying it in different ways to pairs of two.
So, say I have twenty elements, and want to leave the first 6 elements untouched, I slice at 6. Then, I need to apply styles to each of those elements starting at #7, but need to do so in pairs of two. So, elements 7 & 8 will be top: 0; left: 0; while elements 9 & 10 will be top: 240px; left: 240px;
Elements 11 & 12 will then be top: 480px; left: 0; while elements 13 & 14 will be top: 720px; left: 240px;
I hope that pattern makes sense.
I do not know the best way to achieve this. My code is below, however, I only refer to the elements using ‘this’ and in no way am trying to identify pairs. That is what I do not understand how to do.
Here is my example:
$('#main article').slice(6).each(function(i) {
// first pair of two
$(this).css({
top : i * 240 + 'px'
});
// second pair of two
$(this).css({
top : i * 240 + 'px',
left : 480 + 'px'
});
});
Any help is really appreciated. Thanks,
CSS only non-incremental update below original JS answer.
You could change it to use a for loop on the list and increment the index partway through:
Of course you can still use the slice, but you’ll need to position those first 6 elements correctly if you are using position:relative or absolute so that they don’t overlap each other.
Here’s a fiddle showing it working.
Edited from comment discussion below:
If the incremental values aren’t important to you you can achieve the pattern with straight CSS:
Here’s the fiddle for that.