tubaguy50035 tubaguy50035 - 27 days ago 7
jQuery Question

Add a listener to an element that is dynamically added

I have a javascript/jQuery page where I'm using Twitter Bootstrap's typeahead. There are two separate places in the javascript where I add elements that I would like to be typeaheads. Without asking for subjective answers, what's a good way for me to register the inputs as typeaheads dynamically? Give them all different ID's and register every time I add them? Is there any magic that can be done with

.on()
?

Answer

You can use jQuery delegation to do that. For example:

$("#element-that-will-contain-typeaheads").on("DOMNodeInserted", function () {
    $(this).find(".typeahead").typeahead();
});
Comments