Lee Price
Lee Price

Reputation: 5212

jQuery executing JavaScript on dynamically loaded HTML

I have developed a Wordpress site that loads pages dynamically using the .load function.

I have installed a few plugins that I NEED to get working, there is no substitute. My problem is that these plugins rely on JavaScript (an AJAX contact form, and a photo gallery) when they are loaded into div#content the required JavaScript doesn't execute on the dynamically loaded content.

A normal solution would be load the JavaScript I need with the page, but since this is done with Wordpress and the <script> tags are placed in <head> by the plugin. Another solution I have considered is using jQuery's $.getScript, but again since the JS is already in the head this will cause conflicts. I am really stuck as to where to go next.

Any help appreciated guys.

Upvotes: 1

Views: 363

Answers (1)

Didier Ghys
Didier Ghys

Reputation: 30676

Why don't you use the "complete" callback of the .load() method to instantiate your plugins to the added elements ?

 .load( url [, data] [, complete(responseText, textStatus, XMLHttpRequest)] )  

 url: A string containing the URL to which the request is sent.    
 data: A map or string that is sent to the server with the request.    
 complete(responseText, textStatus, XMLHttpRequest): A callback function that is executed when the request completes.

The use is:

$('#insertIntoThis').load('url', function(data, status, xhr) {
    // instantiate here
    // $('#myelement').myPlugin();
});

Upvotes: 1

Related Questions