0

I have problem with following code. I have a div with id reloadDiv that is refreshing every 3 seconds using ajax. Content of the div is loaded using php, there is more content in this div but I didn't added it here.

Div is reloading normally. The problem is with input type button event with class replyComment, there are multiple buttons with this class here. When I add click event the event is working until first reload, as soon as div reloads event is not working any more.

Does someone know how to solve this problem?

<div id="reloadDiv">
     <?php foreach($comments as $c):?>
        <input type="button" value="Reply" class="replyComment" /> 
     <?php endforeach?>
</div>

js:

setInterval(function(){
    $("#reloadDiv").load(location.href + " #replyComment");
}, 3000);

$('.replyComment').click(function(){
    console.log("smth")
});
freedomn-m
  • 27,664
  • 8
  • 35
  • 57
Nemanja
  • 21
  • 4

1 Answers1

0

That happens because content is replaced, and the element with the event doesn't exists anymore, as well the event.

Try this:

$('#reloadDiv').on('click', '.replyComment', function() {

With that, the event is bound to the parent element and will work no matter how many times the content is recreated.

DontVoteMeDown
  • 21,122
  • 10
  • 69
  • 105