13

After asking the same question 2 weeks ago here, I finally found "the" solution. This is why I am answering my own question. ;)

HOW TO BIND, UNBIND AND REBIND EVENTS IN JQUERY?

Community
  • 1
  • 1
John Doe Smith
  • 1,623
  • 4
  • 24
  • 39
  • 2
    Possible duplicate of [jquery rebind() disable events for a specific time, then rebind them](https://stackoverflow.com/questions/13729681/jquery-rebind-disable-events-for-a-specific-time-then-rebind-them) – Sterling Archer Aug 24 '17 at 20:04

2 Answers2

13

And THIS is the perfect solution. (At least for me.)

$(document).on('click', 'a#button', function(){
    $(this).after('<span> hello</span>');
    $('span').fadeOut(1000);
});

$('a#toggle').toggle(
    function(){
        $(this).text('rebind');
        $('a#button').on('click.disabled', false);
    },
    function(){
        $(this).text('unbind');
        $('a#button').off('click.disabled');
    }
);

".on()" does it. NOTE: It is important to bind the event like you can see on line one! It does not work with .click() or …!

See the docs!

Here is a fiddle to try it and experiment with it!

Enjoy!

John Doe Smith
  • 1,623
  • 4
  • 24
  • 39
  • 1
    Why did you repost it if you already answered it on your original question? – Kevin B Dec 18 '12 at 20:04
  • 1
    I guess because the other solution is also nice and useful! (Updated the old post) – John Doe Smith Dec 18 '12 at 20:13
  • Great answer! This certainly helped me temporarily disable a button's click event. And, for additional emphasis, the context of the click event should be how it is shown in the above answer! – Con Antonakos Jul 22 '14 at 20:10
  • Question: why does this work? Are we enabling/disabling a 'disabled' property on the native click event? – Con Antonakos Jul 25 '14 at 18:30
  • 2
    Important! For anyone looking into this, the `.toggle()` method was deprecated in jQuery 1.8 and removed in jQuery 1.9. ([Source - jQuery.com](https://api.jquery.com/toggle-event/)) – Laurence Cooper Mar 09 '16 at 12:13
3

A simpler and short solution is to add a class to the object if you want to unbind it then remove this class to rebind ex;

$('#button').click( function(){
   if($(this).hasClass('unbinded')) return;
   //Do somthing
 });

$('#toggle').click(function(){
    $('#button').toggleClass('unbinded');
 });
Wessam El Mahdy
  • 457
  • 5
  • 14