4

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.

Johanna
  • 39
  • 1

2 Answers2

1

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
  • 184,426
  • 49
  • 232
  • 263
  • 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 Jun 23 '10 at 08:21
0

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.

Community
  • 1
  • 1
Alexis Abril
  • 6,389
  • 6
  • 33
  • 53
  • 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 Jun 23 '10 at 17:05