Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript every nth, create new row

I have a products page that I want to show 3 items in each row and then if it has more, create a new row and show more. So 3 cols per row with unlimited rows. Below is the code that I have that contains my loop which I assume the code will need to go into.

$(data).find('products').each(function() {

            itemName = $(this).find('itemName').text();
            itemDesc = $(this).find('itemDesc').text();
            itemID = $(this).find('id').text();

                items +='<div class="row-fluid">\
                <div class="span3">Col 1</div>\
                <div class="span3">Col 2</div>\
                <div class="span3">Col 3</div>\
                </div>';

            count++;

        });

Here is where I need to do it but I am a little stuck on how to approach this. If the count is dividable by 3 I assume it will then need to create a new row.

Thanks for any help or input you can provide.

like image 525
SBB Avatar asked Sep 17 '13 05:09

SBB


1 Answers

First of all, no need to handle a count variable on your own, the .each() function already supplies an index element (as an optional argument).

With the modulus operator you can get the remainder from dividing the index by 3. Then you can tell when do you need to print the opening of the row and the ending of it.

$(data).find('products').each(function(index) {

    itemName = $(this).find('itemName').text();
    itemDesc = $(this).find('itemDesc').text();
    itemID = $(this).find('id').text();

        if ((index % 3) == 0) items += '<div class="row-fluid">';

        items += '<div class="span3">Col 1</div>';

        if ((index % 3) == 2) items += '</div>';
});

if (items.substr(-12) != '</div></div>') items += '</div>';
like image 126
Itay Avatar answered Sep 19 '22 15:09

Itay