Zach Thacker
Zach Thacker

Reputation: 2608

Re-enable event handler for a link

I want to disable a link while certain conditions exist on the page, but re-enable it once those conditions go away. So I have a function that executes regularly that checks for the condition.

if(!enabled) {
$(button).click(function(){return false;});
}

How do I "re-enable" that click event so that it performs the normal action? All I want it to do is behave like a normal link.

Upvotes: 1

Views: 1007

Answers (4)

kapa
kapa

Reputation: 78671

You can put a custom event namespace on your link, and bind/unbind it when necessary:

Disabling:

$('#thelink').on('click.MyDisable', function () {
    return false; 
});

Enabling:

$('#enabler').on('click', function () {
    $('#thelink').off('click.MyDisable');
});

Please check out the jsFiddle Demo.

Upvotes: 2

ek_ny
ek_ny

Reputation: 10243

I would set the disabled attribute to disabled when you want to disable the link, and remove the attribute when want to enable it. The only problem is the link will appear disabled, but the user can still click on it. So in addition to that in the click event handler I would check for the following condition:

$("#myLink").click(function(){
   if($(this).attr("disabled"))
      return false;
});

in your checks you can either do this:

$("#myLink").attr("disabled", "disabled");//if you want to disable it

$("#myLink").removeAttr("disabled");//if you want to enable it

Upvotes: 0

BumbleB2na
BumbleB2na

Reputation: 10743

You could do your check within the button click:

$(button).click(function(){ 
    if(!enabled) 
        return false;
});

Upvotes: 0

Adam Hopkinson
Adam Hopkinson

Reputation: 28795

Put your condition inside the event:

$(button).click(function(){
    if(!enabled) {
        return false;
    }
});

Upvotes: 0

Related Questions