Neilos
Neilos

Reputation: 2746

How to add events to elements appended by AJAX?

I load some html using AJAX, this works fine, one of the bits that loads is a contact form which I am trying to intercept the submit event using

$(document).ready(function() {    
    $('contact_form').submit(function() {
        return false;
    });    
});

The above javascript is loaded with the initial page load.

However, when I visit the page and submit the form it follows its default path and follows the regular submit (which works but it is my non-javascript compatability route that I want most users not to follow). I have tried testing .click() events on bits of the page that are initially loaded and similar bits that are loaded using AJAX, the result being that only the elements that were initially loaded with the page execute the .click() event.

I'm guessing that it is the fact that I load the jQuery code before adding the elements to the DOM (I have some <script> tags that load with the initial page load) and this is not regestering the listeners propperly (wild guess, I actually don't really have a clue).

Am I correct in my assumption? And what is the best fix?

Upvotes: 2

Views: 1199

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

First of all contact_form isn't a valid selector, as it's looking for a <contact_form> element. It should be #contact_form to select by id, or .contact_form to select by class.

Secondly your assumption about the event handlers is correct, the shortcut event handlers (click, submit etc.) only work on elements available in the DOM on page load.

If the element is appended to the DOM after page load (eg. via AJAX) you need to use delegate() or on() (in jQ1.7+) to add events to that element:

$('body').delegate("#contact_form", "submit", function() {
    return false;
)};

Or:

$('body').on("submit", "#contact_form", function() {
    return false;
)};

I have used body as the parent selector here, but you should use the closest static element (that is one that is available in the DOM on page load) to the one you are placing the event on.

Upvotes: 3

Related Questions