0

I have a written a code to update likes and dislikes buttons. It works fine for the first time. But if the user again clicks on the buttons, It doesn't respond to clicks. I tried changing click to on('click') as suggested in questions of similar type.

$('.like').on('click', function (event) {
    // My Code
});
deltaforce
  • 524
  • 1
  • 8
  • 25

3 Answers3

1

You're doing it wrongly as your code is the same as

$('.like').click(function(e){}). 

They are both using direct events. Dynamically generated elements don't have the events bound to them. But luckily these events bubble up the DOM tree, so you can delegate this to some outer elements. That's the idea of using .on() to create a delegated event:

$(document).on('click', '.like', function(event) {
})
EJAg
  • 3,210
  • 2
  • 14
  • 22
1

What you are currently doing is event handling. You should actually be doing event delegation.

And you need to change your .on click method as,

$("document").on('click', '.like', function(event){ 
    // Put your code here      
});

Hope this helps!

David R
  • 14,711
  • 7
  • 54
  • 72
1

You should use it below, doing event delegation:

$(document).on('click', '.like', function (event) {
    // My Code
});
Milan Chheda
  • 8,159
  • 3
  • 20
  • 35