Need help with this JS code!

navyaries

Junior Member
Joined
Jun 4, 2016
Messages
1
Reaction score
0
Need help explaining this JS code! Anyone able to help?
Thanks!

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++;
});
 

davidktw

Arch-Supremacy Member
Joined
Apr 15, 2010
Messages
13,550
Reaction score
1,302
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);
});
 
Last edited:
Important Forum Advisory Note
This forum is moderated by volunteer moderators who will react only to members' feedback on posts. Moderators are not employees or representatives of HWZ Forums. Forum members and moderators are responsible for their own posts. Please refer to our Community Guidelines and Standards and Terms and Conditions for more information.
Top