0
<!-- Brands -->
<div class="brands">
  <ul class="thumbnails">
    <li class="span3"> <a href="#" class="thumbnail"> hello1 </a> </li>
    <li class="span3"> <a href="#" class="thumbnail"> hello2 </a> </li>
    <li class="span3"> <a href="#" class="thumbnail"> hello3 </a> </li>
    <li class="span3"> <a href="#" class="thumbnail"> hello4 </a> </li>
    <li class="span3"> <a href="#" class="thumbnail"> hello5 </a> </li>
    <li class="span3"> <a href="#" class="thumbnail"> hello6 </a> </li>
    <li class="span3"> <a href="#" class="thumbnail"> hello7 </a> </li>
    <li class="span3"> <a href="#" class="thumbnail"> hello8 </a> </li>
  </ul>
</div>

That's my html code and this is my jQuery code.

$(document).ready(function () {
$('.brands li').click(function () {
    var index = $(this).index();
    alert(index);

    if (index < 4) {
        alert('less than 4');
    }

    if (index > 4 && index < 8) {
        alert('less than 8');
    }

    if (index > 8 && index < 12) {
        alert('less than 12');
    }

  });
});

i'm trying to later on insert a new li after the 4th li if the li is less than the 4nth-child, and then insert an li after the 8th li if the le is less than the 8nth-child and so on. is there any way of simplifying the rather than having a lot of if statements?

Kyle McBride
  • 171
  • 1
  • 8

2 Answers2

1

You can use this to calculate which group it is instead of the if statements:

var group = parseInt((index - 1) / 4) + 1;
alert((group * 4) + " or less");

Or this:

var group = parseInt(index / 4) + 1;
alert("less than " + (group * 4));

Depending what you want as your question doesn't match your example code.

mattmanser
  • 5,719
  • 3
  • 38
  • 50
1

what you can do is:

var section=4*~~(index/4);
$('.brands li:nth-child('+section+')').append('<span>new li</span>');

this will do an integer division on your index, leaving you with the multiple of 4 that fits into your value. https://stackoverflow.com/a/4228528/1260792

Community
  • 1
  • 1
aelgoa
  • 1,193
  • 1
  • 8
  • 24
  • it worked :) but i had to change var section=4*~~(index/4); to var section=4*~~(index/4) + 4; so that it would work to how i wanted it to. – Kyle McBride Jan 30 '13 at 09:55