Dave Merwin
Dave Merwin

Reputation: 1412

How do I get DOM objects loaded via AJAX to fire jQuery attached to new dom objects

I have a dom object that is loaded via $.load(). I then have click functions connected to the object that is loaded.

The click functions won't fire with the new DOM object.

What am I missing?

nothing in the .cntrls a click function is firing.

Here's a sample:

    $('.ati a').click(function() {

    // First, clear out the current content
    if ('.msg-obj' || '.poc-obj' || '.pom-obj || .cntrls') {
        $('.msg-obj, .poc-obj, .pom-obj, .cntrls').hide();
    };

    // Get the URL for the object that is clicked
    var clickedObjPath = $(this).attr('href');

    console.log(clickedObjPath);

    $('#msg').load(clickedObjPath + ' .msg-obj').fadeIn();
    $('.poc').load(clickedObjPath + ' .poc-obj').fadeIn();
    $('.pom').load(clickedObjPath + ' .pom-obj').fadeIn();
    $('.cntrls').load(clickedObjPath + ' .cntrls a').fadeIn();

    return false;
});


$('.cntrls a ').click(function() {

    // Get the URL for the object that is clicked
    var cntrlObjPath = $(this).attr('href');
    console.log(cntrlObjPath);

    return false;

});

Upvotes: 0

Views: 893

Answers (2)

jfriend00
jfriend00

Reputation: 707876

If you install the click handlers before the object actually exists in the page, they won't work unless you use delegated event handling. The code will look for the desired object to hook up its event handler and won't find it so nothing will be hooked up.

In jQuery before 1.7, you would use .delegate() and in jQuery 1.7+, you would use .on() on a parent object that does exist at the time you install the click handlers.

Using .on() (for jQuery 1.7+), you would do it like this:

$(document.body).on('click', '.ati a', function() {...});

Ideally, you'd pick a parent object that was closer to the actual object than the body object and exists at the time you install the click handler, but you haven't included any of your HTML so I don't know what to be pick besides body.

The pre-jQuery 1.7 syntax would be this:

$(document.body).delegate('.ati a', 'click', function() {...});

The old way to do this was using .live(), but that has been deprecated for all versions of jQuery and they recommend .delegate() for pre-jQuery 1.7 or .on() for jQuery 1.7+.

Upvotes: 2

Damen TheSifter
Damen TheSifter

Reputation: 911

Try live event binding $("a").live(..... ) In jq docs

Upvotes: 0

Related Questions