Using JQuery's on() Function to Attach Handlers to Elements now or in the Future

Using JQuery's on() Function to Attach Handlers to Elements now or in the Future

Last updated:

It is very common to need to attach event listeners and callbacks to elements that don't exist yet, when coding in Javascript and JQuery.

With jQuery's on() function, you can accomplish just that.

There's a way to add event handlers to elements that don't exist yet (you may create them later on dynamically)

You can register a container element and a selector and, for every event that the container element catches which comes from an element matching that selector, your event handler will fire up, even though the matched elements weren't present at the time you attached the event handlers.

Here's an example:

Say you start out with an empty <div>:

<div id='my-div'> </div>

And you have added <button>s to that div (after your page has rendered and all your javascript page source has been read) calling methods like add():

$('#my-div').add('<button>a button</button>');

Now you may want to add event listeners to those buttons - but how can you, if they aren't there yet? (If you try and attach a handler using $('#my-div button').click(function(){...}), it won't work because that selector will return nothing so jQuery won't attach any handlers to that events.

Using jQuery's on() method you can add an whatever buttons might get added to that div in the future:

$('#my-div').on('click','button',function(){
    alert('button inside my-div clicked!');
});

Here's a working JSFiddle showing this behaviour.

Dialogue & Discussion