Gary B
Gary B

Reputation: 143

using jQuery to dynamicly reload or switch external js file

I have a webpage where I have an external js file that animates some divs. I want to place a button on the page that reloads the js file from the start so it stops the function and starts from the beginning. I tried giving the script tag the id "animation" and then using the following.

$(document).ready(function() {

$(".button").click(function()
{

    $("#animation").attr('src','map.js');

});
}
);

Needless to say it did not work. Wondering how to do this correctly.

Upvotes: 2

Views: 5361

Answers (1)

nick
nick

Reputation: 3711

This is really not a good thing to do, much better to make a function to start and stop the animation. But if you really really have to:

$(".button").click(function( e ) { 

    //change this to the id of your script
    $('#the_script').remove();

    var script = document.createElement('script');
    script.id = 'the_script';
    //the script's source here
    script.src = 'test_js.js';
    script.type ='text/javascript';
    document.getElementsByTagName('head')[0].appendChild(script);

}); 

Upvotes: 4

Related Questions