Question:
I am trying to fire a .click() event if a <ul></ul> element has no DOM within it.
The thought process behind this code is, when the user clicks the x the item slides left, and then is .remove() from the DOM. As a result of my beautifully whitespaced HTML, its leaving line breaks and spacing within the ul still. As such i can’t get the if() statement to function properly.
Even by using $.trim() and then comparing it still won’t fire the .click() event.
Picture Of The HTML

HTML
<div class="btn-group pull-right nav-notice">
<span class="badge badge-info nav-notice-button">8</span>
<div class="notice-container">
<span class="notice-arrow"></span>
<ul class="notice-container-list">
<li><span class="label label-warning">Warning</span><span class="notice-message">Warning 12315125</span><i class="notice-remove icon-remove-circle"></i></li>
<li><span class="label label-success">success</span><span class="notice-message">Warning 12315125</span><i class="notice-remove icon-remove-circle"></i></li>
<li><span class="label label-important">important</span><span class="notice-message">Warning 12315125</span><i class="notice-remove icon-remove-circle"></i></li>
</ul>
</div>
</div>
jQuery
//live(), looking for past/present DOM
$('.notice-remove').live( "click", function(){
//no double dipping!
$this = $(this);
//Hide the x item, improves the animation a bit
$this.hide();
//animate the width of the li, to give it a slideoff effect
//when the animate completes, remove the element from the DOM
$this.parent('li').animate({
width: "0"
}, 'fast', '',
function(){
$(this).remove();
});
//get the html contents of the ul element
var str = $('.notice-container-list').html();
//trim the contents of the ul, and if they are exactly empty
//fire the click event to close the container
if( $.trim(str) === "" ){
log('Closing the Notice');
$('.nav-notice-button').click();
}
});
I doubt it will work this way. See, you’re checking the element right after you declare some animate functionality for it. But that function will not be called immediately – that’s the whole point of animate()! And this, it turn, means that when you check
<ul>contents, it’s still not empty.Use the following technique instead: check how many elements are left in
<ul>when removing<li>; if there’s none of them, remove the<ul>itself:Here’s a working jsFiddle (had to put something texty in
<i></i>, cannot use your css’ icons). For the same reasons I used simple.parent().remove()instead of triggering the$('.nav-notice-button').click(), as I don’t know what should be done with that click. )