1

I'm looking at using .off() and .on() to turn event handlers off and on in jQuery.

I can turn the all attached event handlers off perfectly by using:

$('.eventone').off();

or as a multiple selector:

$('.eventone, .eventtwo, .eventthree').off();

However, I'm not getting all (or even any) event handlers to turn back on. I'm using this:

$('.eventone, .eventtwo, .eventthree').on();

Is there something I'm doing wrong?

Do I actually have to declare every event that's associated with the class in order to turn it back on?

Kyle Yeo
  • 2,270
  • 5
  • 31
  • 53
  • 2
    Yes. `.off()` doesn't disable events, it removes them completely. – JJJ Aug 18 '13 at 10:23
  • @PatrickEvans what do you mean a global variable? From what I gather, right now using `.off()` is out of the question, am I right? – Kyle Yeo Aug 18 '13 at 10:30
  • If you're really into this behavior, you can save an array connecting events and their elements, the use .off(), and afterwards call a function that runs on your array and returns the events. This might be useful: [jQuery find events handlers registered with an object](http://stackoverflow.com/questions/2518421/jquery-find-events-handlers-registered-with-an-object) – Itay Aug 18 '13 at 10:31
  • @Juhana also, thanks for that little bite of info -- made me realize I was totally climbing up the wrong tree. – Kyle Yeo Aug 18 '13 at 10:39

1 Answers1

3

Yes, .off basically removes the events so you will have redeclare them. you are better off having a global variable so your event handlers can check to see if it set to off or on and if off just return. And just change the variable to off or on, true or false or whatever suits you

var eventsOn = false;
function myFunc() {
   if(!eventsOn) return;

   //Code to run here.
}

//Somewhere else set your events and turn eventsOn to true
jQuery("#mydiv").on("click",myFunc);
eventsOn = true;
Patrick Evans
  • 41,991
  • 6
  • 74
  • 87
  • AHH. I get what you mean now. Thanks! – Kyle Yeo Aug 18 '13 at 10:31
  • 1
    I don't recommend multiline braceless IFs. If you want to go braceless, remove the line break. I you can't fit into one line, add braces. The reason is that these tend to break when copy-pasting stuff. – John Dvorak Aug 18 '13 at 10:40
  • @JanDvorak what you mean would be to do it like this: `function myFunc() {if(!eventsOn){return;}}`, right? – Kyle Yeo Aug 18 '13 at 10:44
  • @Reno Yeo, he just means having the if look like this, `if(!eventsOn) return;` on one line – Patrick Evans Aug 18 '13 at 10:52