Syndicate

Feed

Binding an event listener to a DOM element that may not yet exist

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());
});
Last edited by Caroline Schnapp about 12 years ago.

Comments

Exactly what I was looking for..

.. thanks for posting.

Stunning site design by the way. The header with the cup is the prettiest thing I've seen on the web in a while.

Thank you, Rob!

I am glad this bit of coding and text were useful to you.

website is so great

Your website is so great. More on this website may think I'm surprised. That's how you understand this subject is nice to know.

very nice!!

I appreciate the great information. I arrived on the information I was looking for. Thank you as always.