Need help explaining this JS code! Anyone able to help?
Thanks!
Code:
var i = 1;
$('.tg-item').each(function() {
if (i == 1 || i == 6 || i == 7) {
$(this).data('col', 2).data('row', 1);
} else {
$(this).data('col', 1).data('row', 1);
}
if (i == 7) {
i = 1;
}
i++;
});
For all nodes assigned with class "tg-item" found in the document, assign the 1st, 6th and 7th offset nodes, wrapping around 7 nodes, with data attributes "data-col=2" and the rest "data-col=1". All class "tg-item" nodes will have data attribute "data-row=1".
The last part of the codes can be simply expressed as
i = ( i + 1 ) % 7;
use i + 1 instead of i, or if you like create
j = i + 1; and use j instead
And I will encourage using i starting with zero base instead of one
Go read up
https://api.jquery.com/each/, you don't need to specially use an external index counter, the each function in jquery already supply an iterator index
Consider the following code instead. It does the same thing more concisely and such be more efficient.
Code:
$('.tg-item').each(function(i, o) {
var j = i % 7;
$(o).data('row', 1)
.data('col', (j == 0 ||
j == 5 ||
j == 6)
? 2 : 1);
});