There's a very sweet jQuery plugin that makes it possible to bind event listeners to elements that may not have been added, yet, to the document. It's called livequery and I downloaded the 1.1.x version on github to work with my jQuery 1.3.2. (There's no 1.1.x version among the official releases on the jQuery site.) I used this plugin recently. The context was: another jQuery script was responsible for adding drop-down boxes to my web page. I wanted to do something on my end whenever a new selection was made in these drop-downs.
Just so that I remember... as a note to my future self... There's another way to bind an event to present and future elements, and that way relies on event bubbling:
jQuery(function() { jQuery('#myWrapperDiv').click(function(evt) { var targetedDOMElement = evt.target; if (jQuery(targetedDOMElement).is('#select-0 option')) { doMyThing.call(targetedDOMElement); } }); }); function doMyThing() { console.log(jQuery(this).parent().val()); }
I can bind an event to a container div element that exists already and which will contain my drop-down boxes. As a refresher, Function.call() receives as first argument whatever we want the keyword this, in the function called, to refer to.
The way of the livequery plugin is less verbose somewhat. (Note: some functionality in livequery did make it to jQuery's 'core' but you can't listen to a change event with jQuery.live() yet.)
This code does not need to be run when the DOM is ready:
jQuery('#select-0').livequery('change', function() { console.log(jQuery(this).val()); });