Reputation: 37494
Ok,
so I have:
<ul>
<li>hello</li>
<li>bye</li>
</ul>
Then:
$('li').click(function(){
$(this).remove();
})
But then i have:
if($('ul li').length == 0){
$('ul').append('<li>You haven\'t favourited anything. Get to it!</li>');
}
But it doesn't work!
Upvotes: 1
Views: 320
Reputation: 3582
This will check for list items when the document loads AND if a user clicks away all the list items:
$(document).ready(function() {
checklist();
$('li').click(function(){
$(this).remove();
checklist();
})
function checklist() {
if($('ul li').length == 0) $('ul').append('<li>You haven\'t favourited anything. Get to it!</li>'); }
});
Upvotes: 0
Reputation: 76003
It seems to work fine, here is a jsfiddle: http://jsfiddle.net/pcY54/2/
//use jQuery 1.7's `.on()` function to delegate an event handler to the click event
$('ul').on('click', 'li', function(){
//remove the clicked `<li>` element
$(this).remove();
//check to see if there are any `<li>` elements left
if($('ul li').length == 0){
//if there are no `<li>` elements then add one with a default message
$('ul').append('<li>You haven\'t favourited anything. Get to it!</li>');
}
});
Upvotes: 0
Reputation: 140228
I looked into my crystal ball and this seems to appear to be a dynamic list where you can append elements and then remove them and append again and so on?
If so, you cannot use bind but need to use event delegation in a higher level element like so:
$('ul').delegate("li", "click", function(){
$(this).remove();
if($('ul li').length <= 0){
$('ul').append('<li>You haven\'t favourited anything. Get to it!</li>');
}
})
jsfiddle: http://jsfiddle.net/pcY54/3/
Upvotes: 0
Reputation: 4965
You need to check if any li's are present after you have clicked on them:
$('li').click(function(){
$(this).remove();
checkLiLength()
})
function checkLiLength(){
if($('ul li').length == 0){
$('ul').append('<li>You haven\'t favourited anything. Get to it!</li>');
}
}
Updated fiddle: http://jsfiddle.net/pcY54/1/
Upvotes: 0
Reputation: 17314
I think what you want is to just put that if
block inside the click
handler, so it will re-evaluate after removing an element and then add that message. As it is it just runs once on page load, and never again.
Upvotes: 0
Reputation: 177
$('li').click(function(){
$(this).remove();
if($('ul li').length == 0){
$('ul').append('<li>You haven\'t favourited anything. Get to it!</li>');
}
});
If you put that if statement outside of the call back, it tests for "no li elements" when the page loads, basically. You want it to test for "no li elements" after you have removed one, so the right place to do this is after you remove one. :)
Upvotes: 1