I am having a hard time getting some jQuery functions to work like it should.
I have a like button on my site that works until new items are appended, then it stop to work.
This worked when I had the following code:
$('.like').toggle(
function() {
console.log('href');
}, function() {
console.log('rel');
}
);
A friend of mine directed me to event bubbling, but I am having a hard time getting it to work.
Here is what I have at the moment.
the simple HTML
<button href='123.html' rel='456.html' class='like'>Click here</button>
the jQuery, wrapped in $(document).ready( …
I have tried the toggle function, and it seems like the button is asleep for the first click, then it suddenly wakes up and performs the event.
$('body').click(function(event) {
if ($(event.target).is('.like')) {
var $like = $(event.target);
$like.toggle(
function() {
console.log('href');
}, function() {
console.log('rel');
}
);
}
});
What should the code be like in order to keep working when new items are appended and make sure that the button does not act this way
Here is a fiddle.
The thing is, we can’t delegate “toggle”, because toggle is not an event, it’s just a method in jQuery. So you need to implement your own toggle functionality for delegated events.
Sample solution:
I’d also suggest changing the selector in the above code from “body” to parent container of .like elements, so the delegation has shorter way up the document tree.
and a sample fiddle: http://jsfiddle.net/t2pXr/3/