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 2 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.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <css> <html> <javascript> <mysql> <php> <span> <a> <b> <i> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <sup> <sub> <dd> <del> <blockquote> <img> <q> <p> <div>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <css>, <html>, <javascript>, <mysql>, <php>, <rails>, <ruby>.

More information about formatting options

CAPTCHA
I have to wonder if you're a human spammer or a machine, or less likely someone who cares to leave his or her thoughts behind.