Tuesday, November 20, 2012

Using jQuery .on() rather than .onClick on dynamically generated buttons

Last week, I was beating my head over why the .click() event wasn't working with a dynamically generated button. My setup was that the buttons were given the class 'do_this' and the javascript looked like:

$('.do_this').click(function(){ /* insert code here */ }; 

At first I thought maybe it was because the code wasn't inside $(document).ready(), so I put it inside one. Didn't work. Then I tried assigning the attribute and value 'onClick="runThisFunction()"' to the button instead. Still no go. (I also thought maybe I should define the Javascript functions after the buttons were generated, so I did just that. I'm not sure why it didn't work, though. It could be because the JS that rendered the buttons happened through a .post call.)

Then my co-worker pointed me to the jQuery .on() method. Surprise, surprise: it worked! The code looks like this now:

$(document).on("click", '.add_contact', function(event) { /* insert code here */ });

The jQuery documentation goes on to explain why .on() works and none of my previous attempts did:
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.
See? I put everything inside document so the class was already rendered when the Javascript bound the class to the click event.

So with that in mind, happy coding!