Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to get jQuery on() to register dynamically added content

I'm quite new to the on() method in jQuery but the time has come for me to need to use it.

I've two functions for clicking on specific buttons. Each function works on any elements originally on the page but not on any dynamically added content (more of the same buttons). I understand I need to use the on() function after reading other answers on here and on Google but am having trouble still. Anyway, code:

jQuery("ul#THEBUTTONS").on({
    click: function(event){
        event.preventDefault();
        console.log("apaz clicked");
    }
}, "a.azaz");


jQuery("ul#THEBUTTONS").on({
    click: function(event){
        event.preventDefault();
        console.log("mapaz clicked");
    }
}, "a.mapaz");

Any help would be immensely appreciated, tearing my hair out here.

like image 436
tristyb Avatar asked Mar 14 '12 09:03

tristyb


2 Answers

.on() essentially has two flavors: one which acts like .bind(), and another which acts like .delegate().

For your problem, you want to use the delegate version. As a reference, on signatures are like this:

// bind
$(element-selector).on(event, handler)

// delegate
$(container-selector).on(event, element-selector, handler)

The best way to get up to speed with this is probably to read up on delegate, what it is, how its used, and then apply that to on.

like image 95
Richard Neil Ilagan Avatar answered Nov 15 '22 07:11

Richard Neil Ilagan


There are two ways to use .on(), and you're using the wrong type.

You can bind event handlers directly to elements using $('selector for elements you want the event handler bound to').on('event', function() {...});

Or, you can delegate events, by calling .on() on a wrapper element that will contain all of the dynamically added elements, such as a div or, in the worst case, the <body> element. Code would look something like this:

<div id="wrapper">
    <a href="#" class="link">Test link</a>
</div>

$('#wrapper').on('click', '.link', function(e) {
    // code to handle the click event on the link here
});

The event handler is actually handled by the <div id="wrapper"> element once the event has bubbled up to it, but the function is only called if the original target matches the selector provided. With this method, you can dynamically add additional elements with the class link to the div, and the function will also run when they're clicked on.

like image 34
Anthony Grist Avatar answered Nov 15 '22 07:11

Anthony Grist