I have a page with a set of comments on an article and a jquery code that lets me edit a comment when i click on it:
comments.js.coffee
$ ->
$(".comment").click ->
html = '''
<form accept-charset="UTF-8" action="/comment?id=''' + $(this).data('value') + '''" data-remote="true" id="updt_comment_form" method="post">
<textarea name="content"> ''' + $(this).children('p').text()+ ''' </textarea>
<input name="commit" type="submit" value="Save">
</form>
'''
$(this).hide()
$(html).insertAfter($(this))
When i submit this form (remotely), the following is rendered:
comments/update.js.erb
$('#comments').replaceWith('<%= escape_javascript(render("comments", :layout => false)) %>');
$('#fresh_comment').show();
$('#fresh_comment').effect("highlight", {}, 3000);
After i submit this form, the jquery code in comments.js.coffee stops working. The next time i click in a comment, i won’t be able to edit it, unless i reload the page (which defeats the purpose of using ajax).
Is this normal? Am i doing something wrong?
The only solution i can think of is resetting the jquery trigger in update.js.erb to make it work again… but that doesn’t seem right.
I don’t see why ANY of my jquery code stops working after executing ANY remote call.
Thanks in advance!
You need to delegate the click handler to a container element, e.g.:
When you replace your
.comments via.replaceWiththe original click handlers are no longer present. Event delegation means that attached handlers will always work since the handler is bound to a container element, which is not replaced.Reference:
Note: You can also use
.livefor this, but.delegatehas several advantages over it.