Search code examples
javascriptjqueryjquery-on

Is it possible to get an attribute from an element when using .on() for dynamically loaded content?


On a site that I'm building for someone, I am making most internal links use pushState since it is a faster user experience. I'm having a problem with getting the href attribute from an anchor <a> element that is loaded dynamically. People always tell me to use .on() rather than .live() because .live() is deprecated, but then I run into problems like this.

Here's my code:

$('#artists').on('click', '.artist a', function(e) {
        SM.config.loader.show();
        var href = $(this).attr('href');
        SM.loadContent(href,'artist');
        history.pushState('', 'New URL: ' + href, href);
        e.preventDefault();
});

There is no href attribute being returned (obviously) so the URL is not changing.

Basically my question is how do I get the href attribute from the element in the second parameter of the on event?


Solution

  • This code is working for me: http://jsfiddle.net/NcZ22/2/

    HTML

    <div id="artists"></div>​
    

    JS

    //Bind an event
    $('#artists').on('click', '.artist', function(e) {
            e.preventDefault();    
            var href = $(this).attr('href');
            console.log(href);
    });​
    
    //Add the element to the dom
    $('<a />', {
        href: 'http://stackoverflow.com',
        text: 'SO',
        class: 'artist'
    }).appendTo('#artists');
    

    Also, make sure you are using jQuery 1.7+ You can read more about .on vs .delegate here http://api.jquery.com/delegate/

    Simple comparison of syntax:

    $(selector).live(events, data, handler);                // jQuery 1.3+
    $(elements).delegate(selector, events, data, handler);  // jQuery 1.4.3+
    $(elements).on(events, selector, data, handler);        // jQuery 1.7+