1

I am trying to create a messages widget that opens a message when the user clicks on its div and that gets refreshed every 30 seconds.

The problem is that after the widget gets refreshed the click functionality stops working. I am guessing that it has to do with the fact that the new elements added were not present when the click was set. And I tested it with firebug, if I run the script after the reload it works until the next refresh.

Does anyone know what is the proper way of resetting something like that after an ajax call?

I include my coffeescript code below:

refreshPartial = ->
  $.ajax url: "refresh-messages-feed"

$(document).ready ->
  myElem = document.getElementById("messagesFeed")
  setInterval refreshPartial, 30000  if myElem?
  $(".conversation").click ->
    url = "/conversations/small/" + $(this).attr("id")
    console.log url
    $.ajax
      url: url
      cache: false
      success: (html) ->
        $("#conversation").html html
Panagiotis
  • 401
  • 4
  • 13

1 Answers1

8

Use a delegated event handler instead:

$(document).on('click', ".conversation", function(){
     // Your handler code
});

This works by listening for the event at a non-changing ancestor element, then applying the jQuery filter to any elements that generated the event, then applying the function to any elements that matched and generated the event.

Note: Use the closest non-changing ancestor for efficiency, or document as the fallback. Do not use 'body' as it has some bugs

iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202