Getting last element in same line

298 views Asked by At

I have this code where i want to insert the div after the line in which element is present.I'm able to do do this for the last element in the line. The problem is i'm not able to figure how to do it for rest of the elements in same line

HTML

<div class="wrap">
  <div class="info"></div>
    <div class="info"></div>
    <div class="info"></div>
    <div class="info"></div>
    <div class="info"></div>
    <div class="info"></div>
    <div class="info"></div>
    <div class="info"></div>
    <div class="info"></div>
    <div class="info"></div>
    <div class="info"></div>
    <div class="info"></div>
    <div class="info"></div>
    <div class="info"></div>

    <div class="newdiv"></div>

CSS

.wrap{border:1px solid #000;width:630px}
.info{border:1px solid red; width:180px;float:left;margin-left:20px;height:100px;margin-top:20px}
.newdiv{width:100%;height:100px;background:green;display:none;float:left}
.active{background:brown}

Jquery

$('.info').on('click',function(){
  $('.info').removeClass('active');
  $(this).addClass('active');

  if(($(this).index('.info')+1)%3===0)
  {
    $('.newdiv').insertAfter($(this)).show();
  }

});

Demo http://jsbin.com/AvERUpU/1/

2

There are 2 answers

0
Peter van der Wal On BEST ANSWER

Calculate the index of the 3thd element:

  var index = $(this).index('.info');
  var afterIndex = index - index % 3 + 2;
  var all = $('.info');
  if (afterIndex >= all.length) {
     afterIndex = all.length - 1;
  }
  $('.newdiv').insertAfter(all.eq(afterIndex)).show();

http://jsbin.com/AvERUpU/4/

1
Rajaprabhu Aravindasamy On

Just a simple math.

Try this,

$('.info').on('click',function(){
  $('.info').removeClass('active');
  $(this).addClass('active'); 
  var xIndexAdded = $(this).index('.info') + (2 - ($(this).index('.info')%3));     
  $('.newdiv')
     .insertAfter(($('.info').eq((xIndexAdded>=$('.info').length)?$('.info').length-1:xIndexAdded))) 
     .show();  
});

DEMO