Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable and Enable ALL Hyperlinks using JQuery

I have the below which disables all hyperlinks but after an event I want to enable them back all again, how can I do this?

$("a").click(function() { return false; });

I don't think its as simple as just setting it to true. ;)

Thanks all

like image 460
Abs Avatar asked Feb 04 '10 19:02

Abs


3 Answers

Instead of binding your "click" handler that way, do this:

$('a').bind("click.myDisable", function() { return false; });

Then when you want to remove that handler it's easy:

$('a').unbind("click.myDisable");

That way you avoid messing up other stuff that might be bound to "click". If you just unbind "click", you unbind everything bound to that event.

edit in 2014 — the way you bind events now is with .on():

$('a').on('click.myDisable', function() { return false; });

Probably it'd be better to do this:

$('a').on('click.myDisable', function(e) { e.preventDefault(); });

To unbind:

$('a').off('click.myDisable');

Finally, you could bind a handler to the document body and deal with <a> tags that are dynamically added:

$('body').on('click.myDisable', 'a', function(e) { e.preventDefault(); });

// to unbind

$('body').off('click.myDisable');
like image 160
Pointy Avatar answered Nov 07 '22 22:11

Pointy


Try this:

// Better to use the live event handler here, performancewise
$('a').live('click', function() {... return false;});

// Now simply kill the binding like this
$('a').die('click');

bye

like image 6
aefxx Avatar answered Nov 08 '22 00:11

aefxx


Binding and unbinding takes some overhead.

A different solution would be to add a class like disabled, then use hasClass('disabled') to test and see whether or not it should return false.

$('a').addClass('disabled');
$('a').click(function() {
    if($(this).hasClass('disabled'))
        return false;
});
like image 5
user113716 Avatar answered Nov 07 '22 22:11

user113716