I have a project where I need to display elements in rows of 4, and when an element is deleted, I want the remaining elements to shift up. To achieve this, I am currently assigning a class "last" to every fourth item after a deletion and inserting a spacer div below the row (after the last element).
Check out the fiddle here: http://jsfiddle.net/yNA4J/1/
Here's the code snippet:
HTML:
<section class="Con1Artists" id="show">
<article class="topHeadingTitle">
<article class="vieAllTitle"><a id="show2" href="#"><span>View All</span></a></article>
</article>
[....]
</article>
</section>
CSS:
.MusicianCol {
display: block;
margin: 0 0 50px;
}
.boxBg {
background: #fff;
border-radius: 6px;
box-shadow: 1px 2px 1px 0 rgba(0, 0, 0, 0.1);
-moz-box-shadow: 1px 2px 1px 0 rgba(0, 0, 0, 0.1);
-webkit-box-shadow: 1px 2px 1px 0 rgba(0, 0, 0, 0.1);
margin: 0 3% 0 0;
width: 22%;
float: left;
}
[....]
JQuery:
//Remove artist
$(".remove-artist").click(function(event) {
event.preventDefault();
var id = $(this).find("i.fa-times").attr('id');
var likeid = id.replace( /^\D+/g, '');
$("#box-"+likeid).hide('slow', function() {
$("#box-"+likeid).remove();
$('.spacer').remove();
$('.boxBg').each(function() {
$(this).removeClass('last');
console.log($(this).index());
console.log($(this).attr('id'));
if (($(this).index() + 1) % 4 == 0){
$(this).addClass('last');
$('<div class="spacer"></div>').insertAfter($(this));
}
});
});
});
//Show more artists
$('#show2').click(function(event){
if($(this).hasClass('showing')) {
$(this).removeClass('showing');
$('.past').hide();
$('.spacer').remove();
$(this).find('span').html("View All");
}
else {
$(this).addClass('showing');
$('.past').show();
$('<div class="spacer"></div>').insertAfter($('.last'));
$(this).find('span').html("View Less");
}
event.preventDefault();
});
However, while testing with 16 elements and deleting the 8th one, the console.log($(this).index())
results were not as expected:
0
1
2
3
5
6
7
9
10
11
13
14
15
17
18
An issue arises where it skips an index after the first row for every third element, leading to rows of 3 instead of 4 being displayed. Can anyone identify what might be causing this problem? Your assistance is appreciated.