doitlikejustin
doitlikejustin

Reputation: 6353

jQuery's .load() function breaks modal from opening after .load() completes

I am using jQuery's .load() method and Loading Page Fragments. Below is my current code:

$("#submit").click(function() {
    $("#results").load('/ajax/box/ #box');
});

This code is in a moda, which is called when a.ajax-modal is clicked. The problem is that when .load() has completed, the a.ajax-modal in #box that was loaded into #results is not working... it doesn't not open the modal but instead just opens a new page. It seems like the contents of #box are not bound/attached to any event handlers.

Here is an outline of what is happening:

  1. Load page
  2. Click on a.ajax-modal and modal shows
  3. Submit form in modal, run .click() function in modal
  4. Content in #results on page refreshes
  5. Click on new a.ajax-modal that was loaded in #results but modal does not show

Why is the modal not opening after .load() is complete?

Upvotes: 1

Views: 819

Answers (1)

L105
L105

Reputation: 5419

No event has been added to your element because events are added when the document is ready. You need to use .on() method of jQuery to prevent this.

$(function()
    $(document).on('click', 'a.ajax-modal', function() {
       // Your code here.
    });
});

So the event is added to document instead of the element itself.

Upvotes: 4

Related Questions