tags:

views:

52

answers:

3

I would like to know if it possible (and how) to stop a jQuery script on a click event.

I am loading it on a click like this

$("#id_button").click(function() { $.getScript("script.js"); alert ("The script is activated"); });

And I'd like to stop it in the same way.

+1  A: 

I am not sure whether you are lokking for this one or not.

You can bind and unbind an event using jquery like

$("#id_button").bind("click", function(){
});

and for unbind

$("#id_button").unbind("click");
rahul
Well, I tried that but it didn'work. I didn't do a bind before, but in the specification it seemed we could use unbind without bind before.What I did is :$("tr").click(highlight);$("#stop_script").click(function() { $("tr").unbind("click");});But it doesn't change anything
Johanna
A: 

Once you've loaded a javascript, you can't cancel it. Lets say, we have a script like

<script language="text/javascript" id="ourtest">
   function callme(){
      alert('yay');
   }
</script>

We now could call

$(document).ready(function(){
    callme();
});

which would alert us like expected. We also can do something like

$('#ourtest').html('');

or

$('#ourtest').remove();

which would work (we can overwrite the html and even remove the whole script block), but the code was already executed and its loaded into memory. So the function callme() would still work.

Long story short, you can't make an undo for a script block unless you reload the page.

jAndy
A: 

If this is regarding the dynamic "unloading" of a js file, you could apply Jonathan Sampson's approach.

Basically "script.js" could be encapsulated in an object and upon "click", dynamically loaded. On the next click event, different button click or event of your choice, you can set that object to null, removing that script's capabilities.

Edit: Rebecca Murphy's slides on code organization.

Alexis Abril
That seems like a good idea, but how would you do that ?
Johanna
I'm assuming script.js has some methods you're using after your event has fired. You could take these methods and place them inside an object and instantiate the object onclick, instead of loading the *.js file. Then, to remove it, just set that object to null. I'm borrowing from greater minds than my own of course, Rebecca Murphy has a great writeup on the subject. She focuses on code organization, but moving code into "objects" gives you a little more power and might make what you're looking into a bit easier.
Alexis Abril