Ian W
Ian W

Reputation: 990

embedded js files don't work on jQuery .load() content

I have the following code in my index.html file:

<div id="page-insert"></div>
function openPage(pageid) {
  $('#page-insert').load(pageid);
}

openPage('testpage.html');

There is also a few script files embedded on index.html such as jQuery, of course, and some plugins, such as Select2. None of my plugins work on the content after it is loaded into the div. It appears as if the embedded JS files don't apply to the content loaded through jQuery. How do I get the files to apply to this content?

Upvotes: 1

Views: 72

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337570

Any plugins you use will only be instantiated on the content available in the DOM when the page loads.

To instantiate plugins on dynamically loaded content you'll need to use the callback of load(), like this:

function openPage(pageid) {
  $('#page-insert').load(pageid, function() {
    $(this).find('select').select2();
    // other plugins here...
  });
}

Also note that if you have event handlers which should be attached to content added dynamically, you should use delegated event handlers.

Upvotes: 1

Related Questions