Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript line break after 5 increments!

I'm stuck.... Yet again. I need to add a line break after every 5 increments using javaScript. For example

img1        img2         img3         img4        img5
img6        img7         img8         img9        img10

Here is what i was thinking of.

for (i = 0; i < blah.length; i++) {
    imgholder.innerHTML += i;
    if (i > 5) {
        imgholder.innerHTML += '<br>';
    }
}

Ok, I do realize it is not the most structured piece of code (so I'm sorry), but it is just a sample. Hope it made sense. Feel free to ask more questions for clarification.
Cheers,
Sam

like image 781
sam Avatar asked Dec 10 '22 10:12

sam


1 Answers

That will break after element 6, 7, 8 (zero-based, so add 1 to get the image number) and so forth since they're all greater than 5. So you'll get:

img1   img2   img3   img4   img5   img6   img7
img8
img9
img10

You need to replace:

if (i > 5) {

with:

if ((i % 5) == 4) {

so that it breaks after element 4 (img5), 9 (img10), 14 (img15) and so on.

And, since you asked for an explanation, the modulo operator gives you the remainder when you do a division. So 12 % 5 can be worked out as what's left over when you divide 12 by 5. 12 / 5 gives you 10 with a remainder of 2, so 12 % 5 is 2.

The following table may help:

  i  | i % 5
-----+------
  0  |   0
  1  |   1
  2  |   2
  3  |   3
  4  |   4 *
  5  |   0
  6  |   1
  7  |   2
  8  |   3
  9  |   4 *
 10  |   0
 11  |   1
 12  |   2

You can see it cycling through the values {0, 1, 2, 3, 4} so we just have to pick the value where you want to insert the breaks (after 4, marked with *).

like image 136
paxdiablo Avatar answered Jan 30 '23 20:01

paxdiablo