Johan
Johan

Reputation: 35213

Run function on html loaded using ajax

If i load a html document in to a div tag for example, is there any way to call a function that i know exists in the loaded html?

Something like this:

$('#foo').load('bar.html', function(){
    //call a function in bar.html
});

Upvotes: 4

Views: 148

Answers (1)

Sarfraz
Sarfraz

Reputation: 382836

You put your JS code in separate file (you load it in your loaded html file) and use getScript like this:

$('#foo').load('bar.html', function(){
    $.getScript("js/fileName.js");
    // call a function from fileName.js
});

So create a separate JS file (good practice not to mix with html or html document) and call it inside your bar.html file:

<script href="js/fileName.js"></script>

With this, you can also get that file to work with load using getScript.

Upvotes: 5

Related Questions