tep
tep

Reputation: 181

how to unbind and bind again

$("#archive").click(function(event){
        /*do something*/
});

$('#archive2').unbind('click',event);

i have this click function that I unbind. however, i want to bind it again when i click a certain button.

$("#archive").bind("click",event);

im using this code to bind again, however it doesn't seem to work. any suggestions or workarounds?

Upvotes: 2

Views: 16844

Answers (5)

Try this:

var closeHandle = function () {
      alert('close');        
};

function addClick() {       
         $("#btnTest").unbind('click').click(closeHandle);          
}

Upvotes: 0

Tim Büthe
Tim Büthe

Reputation: 63734

As of jQuery 1.7 you should use on and off for all your event handler binding:

var handler = function() {
  alert('The quick brown fox jumps over the lazy dog.');
};
$('#foo').on('click', handler);
$('#foo').off('click', handler);

Upvotes: 3

KTF
KTF

Reputation: 1379

You need to provide a handler to the function so you can bind/unbind from it. (Also allows you to bind/unbind specific events handlers within the same event:

var handler = function() {
  alert('The quick brown fox jumps over the lazy dog.');
};
$('#foo').bind('click', handler);
$('#foo').unbind('click', handler);

(used from http://api.jquery.com/unbind/ )

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816422

You have to keep a reference to the function (instead of passing an anonymous function):

function handler() {
    // do something
}

$("#archive").click(handler); // bind the first time
$("#archive").unbind('click', handler); // unbind
$("#archive").click(handler); // bind again

Not sure what is event in your case, but if it is the event object passed to the event handler then it does not make sense to pass it to unbind and bind.

Upvotes: 6

Daniel A. White
Daniel A. White

Reputation: 190945

Why not have a boolean value and an if statement in the event handler?

Upvotes: 0

Related Questions