Rabin Lama Rabin Lama - 3 months ago 8
HTML Question

show() method removes the html element from dom instead of displaying it

I have this code,

HTML and php

<?php for($i = 1; $i <= 5; $i++) { ?>
<div class="file-add-row" style="display:none;">Some content</div>
<?php } ?>
<div id="add-file-plus">Add File</div>


and the JS is

$('#add-file-plus').live('click', function () {
if($('div.file-add-row:visible').length == 0) {
$('div.file-add-row:hidden:first').show();
} else {
$('.file-add-row:hidden:first').removeAttr("style").insertAfter($('.file-add-row:visible:last'));
}
});


Now, my problem is, when I click the add button for the first time, the first 'file-add-row' div is displayed. But when I click the add button the second time, nothing happens on the page. Instead, it just completely removes that div from the dom.

I am just a beginner in jquery, so there might be things I overlooked. Anyone got any idea about what's going on ?

Answer

When you do:

$('.file-add-row:visible:last')

Just after:

$('.file-add-row:hidden:first').removeAttr("style")

They both refer to the same object. And if you try to insert an object after itself, it will end up removing itself from the DOM.

Change the JS to:

$('#add-file-plus').live('click', function () {
  if($('div.file-add-row:visible').length == 0) {
    $('div.file-add-row:hidden:first').show();
  } else {
    var last_visible = $('.file-add-row:visible:last')
    $('.file-add-row:hidden:first').removeAttr("style").insertAfter(last_visible);       
  }
});

Demo (Click on 'Add File'): https://jsfiddle.net/woxd2jbf/1/

Comments