Take the 2-minute tour ×

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"
share|improve this question
That's some fine unreadable code you have there –  Raynos Apr 5 '12 at 22:55

1 Answer 1

up vote 3 down vote accepted

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 $ ->

share|improve this answer
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 Apr 5 '12 at 22:53
@Jasper's explanation is better than mine. –  Fresheyeball Apr 5 '12 at 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. –  protolif Apr 5 '12 at 23:12
You were right about the direct parent, btw. –  protolif Apr 5 '12 at 23:41

Your Answer


