How to unobtrusively bind a function to an element's click when the element was created with AJAX

Go To StackoverFlow.com

0

I have a nested form in my app that uses AJAX to load an additional sets of fields. One of those fields is a file upload that I want to hide and effectively replace with a text field for pasting a Youtube link. It works for the first sets of fields, however since the function is bound on document.ready, it doesn't work for new AJAX fields. I need to bind it some other way. What do?

$ ->
  $(".foo").click ->
    $(this).css "display", "none"

Update: I wasn't having luck, so I went to read the jQuery .on() documentation, and it reminded me of what Fresheyeball said about binding it on to a parent div. After that, it worked perfectly. Thanks for the great advice!

$ ->
  $("#create").on "click", ".foo", ->
    $(this).css display : "none"
2012-04-05 22:43
by James Dunn
That's some fine unreadable code you have ther - Raynos 2012-04-05 22:55


3

The new jQuery .on should work for you:

$(document).ready ->
   $(window).on 'click', '.multiswitchr', ->
      that = $(this)
      that.css display : 'none'
      that.closest(".fields").find(".f-upload").first().css          display : "none"
      that.closest(".fields").find(".attachment-holder").first().css display : "none"
      that.closest(".fields").find(".youtube-link").first().css      display : "inline"

The way this work is it binds the listener to window (or you can use the direct parent) to listen for the existence of .multiswitchr and binds the 'click' event to it.

P.S. in coffeescript the shorthand for document ready is just $ ->

2012-04-05 22:50
by Fresheyeball
This is called event delegation and the event handler is actually bound to the initial selection, in this case that would be the document element. When an event bubbles-up to the initial selection, the selector passed to the .on() (second argument) function is checked against and if it matches the target of the event, the event handler fires (in a manor that makes this inside the event handler reference the delegated element) - Jasper 2012-04-05 22:53
@Jasper's explanation is better than mine - Fresheyeball 2012-04-05 22:54
Thanks guys for the awesome tips. You really seem to know your stuff. Not sure what my problem is though. My function doesn't appear to be doing anything at all now. I'm going to edit my question for greater simplicity and readability. We'll see if that helps - James Dunn 2012-04-05 23:12
You were right about the direct parent, btw - James Dunn 2012-04-05 23:41
Ads