beefchimi
beefchimi

Reputation: 1308

jQuery Slice Function / Each Pair of Two

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,

Upvotes: 2

Views: 1351

Answers (2)

DigTheDoug
DigTheDoug

Reputation: 1440

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:

var el = $('#main .article');
for(var i=0; i <= el.length; i++){
    var left = (i == 0) ? 0 : i * 40;
        $(el[i]).css({
            top: i * 40 + "px",
            left: left + "px"
        });
        i++;
        $(el[i]).css({
            top: i * 40 + "px",
            left: left + "px"
        });
}​

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:

.article:nth-child(4n-1),
.article:nth-child(4n-1) + li{
    opacity: 0.4;
}

Here's the fiddle for that.

Upvotes: 1

Sam Tyson
Sam Tyson

Reputation: 4626

Pretty easy to do - there is just a bit of code that you need in your .each loop:

var pair = 0;
$('#main .article').slice(6).each(function(i) {
    var second = i%2 > 0;
    var topPx = (20 + (pair * 24)) + 'px';
    var leftPx = (pair * 24 + (second? 20 : 0)) + 'px';
    $(this).css({ "top": topPx, "left": leftPx });
    if(second) pair++;
});

This uses the mod operator to see if the item is the 2nd one of the pair, and will base the top position on that pair value. The left position gets adjusted slightly so it can be seen. I adjusted the number of pixels to fit the jsFiddle view.

Here is a working jsFiddle.

Upvotes: 0

Related Questions