rob.m
rob.m

Reputation: 10571

Add new div every 3

The focus is on the else bit, I am adding a div $('<div id="content" class="span4"></div>').appendTo('.new');, I need to check if I already added 3 divs, and if so, add a new $('<div class="row-fluid new"></div>').insertAfter($row); and then start again

$(".navMore li a").on("click", function() {
    var $el = $(this);
    $('#content').removeAttr('id');
    var $row = $el.closest('.row-fluid');
    if($row.next('.new').length){
        $('<div id="content" class="span4"></div>').appendTo('.new');
    }
    else {
         $('<div class="row-fluid new"></div>').insertAfter($row);
         $('<div id="content" class="span4"></div>').appendTo('.new');
    }
});

Upvotes: 1

Views: 314

Answers (2)

rob.m
rob.m

Reputation: 10571

Used this:

$(".navMore li a").on("click", function() {
var $el = $(this);
$('#content').removeAttr('id');
var $row = $el.closest('.row-fluid');
var $rowNew = $row.next('.new');

if ($rowNew.children().length >= 3) {
        $('<div class="row-fluid new"></div>').insertAfter($row);
}

if($row.next('.new').length){
        $('<div id="content" class="span4"></div>').appendTo('.new');
}
else {
        $('<div class="row-fluid new"></div>').insertAfter($row);
        $('<div id="content" class="span4"></div>').appendTo('.new');
}
});

Upvotes: 0

LNendza
LNendza

Reputation: 1410

I would do something like this using modulus (Operators/Modulus.htm">http://www.java2s.com/Tutorial/JavaScript/0040_Operators/Modulus.htm):

$(".navMore li a").on("click", function() {
    var $el = $(this);
    $('#content').removeAttr('id');
    var $row = $el.closest('.row-fluid');

    var count = $('.new').find('span4').length;

    if (count % 3 == 0)
        $('<div class="row-fluid new"></div>').insertAfter($row);

    if($row.next('.new').length){
        $('<div id="content" class="span4"></div>').appendTo('.new');
    }
    else {
         $('<div class="row-fluid new"></div>').insertAfter($row);
         $('<div id="content" class="span4"></div>').appendTo('.new');
    }
});

This is rough and probably needs some massaging, but I think this is what you're looking for.

Upvotes: 1

Related Questions