Bind on(keyup) to dynamic elements in jQuery (Twitter Bootstrap + typehead)

Jean-Philippe Murray picture Jean-Philippe Murray · Mar 18, 2012 · Viewed 70.7k times · Source

I guess some of you must have frowned eyebrows reading this title eh ? I'm sure people asks this every time, yet, I haven't seen my particular question around so, I'm trying ! Binding events to dynamically created elements is my kryptonite, I just can't wrap my head around it ...

So ok, I'm using Twitter Boostrap, with the typehead() plugin. I'm using this trick to make it work with remote sources of data. At this point, everything work. I click on a text input in my form, tagged for it, and the scripts go load external sources and the drop down appears. But I have dynamic element creation, and you've figured, it just won't work on them. I was exploring the live() method, but looking at "how" the scripts is getting fired, I'm just not sure how I can implement it.

$('#anInputField').typeahead().on('keyup', function(ev){
 // stuff happens
});

Every time there is a keyup, the script fires a jSON request, checks his things, and gets the result back to typehead() who does the autocomplete part of the job. So how can I say to jQuery to look at #aDropdownID created after the initial binding? I went on and checked if I could use live(), but since on() replaces it... I'm clueless !

Any help appreciated !

Answer

elclanrs picture elclanrs · Mar 18, 2012

For on() to be able to delegate you have to call it on a static element that you know is always going to be there and then you pass the dynamic element like:

$('#static-parent').on('keyup', '#aDropdownID', function(ev){
 // stuff happens
});

If you don't have a static parent element, then you can always use body.