292

Anyone know how to disable a link in jquery WITHOUT using return false;?

Specifically, what I'm trying to do is disable the link of an item, performing a click on it using jquery which triggers some stuff, then re-enabling that link so that if it's clicked again it works as default.

Thanks. Dave

UPDATE Here's the code. What it needs to do after the .expanded class has been applied is to re-enable the disabled link.

$('ul li').click(function(e) {
    e.preventDefault();
    $('ul').addClass('expanded');
    $('ul.expanded').fadeIn(300);
    //return false;
});
Leo
  • 35,628
  • 7
  • 72
  • 96
davebowker
  • 4,315
  • 7
  • 25
  • 32
  • 7
    Why the requirement not to use return false? Use it, and then delete the event handler when it no longer applies (or put a conditional in it to return different values depending on the status of the mentioned "some stuff"). – Quentin Jun 09 '09 at 14:33
  • Are you just trying to do some pre-processing before the link is followed on the same click action? i.e. you aren't proposing two clicks but rather user clicks link, some actions happen, link is followed? – Lazarus Jun 09 '09 at 14:36
  • Otherwise, can you explain why you are taking this approach as a better understanding of the problem space will improve the answers. – Lazarus Jun 09 '09 at 14:38
  • @lazarus, I'm proposing 2 clicks on the same link. 1 to do some stuff first, then the 2nd to treat the link as a link. – davebowker Jun 09 '09 at 14:45
  • @daviddorward, So far I've tried return false and it carries on through to the second part of my goal, ie not allowing the 2nd click to go through. If you could write a short example I'd be most grateful. – davebowker Jun 09 '09 at 14:46
  • @David Dorward return false only works if there are no errors. It makes it very difficult to debug when the page reloads before you can see what happened. – Jeff Davis Jun 23 '10 at 22:22
  • I have this same issue, and removing 'href' doesn't work well for me in my case because I may need that value. Therefore, I was considering positioning an opacity:0 DIV on top of the hyperlink temporarily. One would have to implement cross-platform opacity:0, however. – Volomike Apr 19 '11 at 05:24

17 Answers17

370
$('#myLink').click(function(e) {
    e.preventDefault();
    //do other stuff when a click happens
});

That will prevent the default behaviour of a hyperlink, which is to visit the specified href.

From the jQuery tutorial:

For click and most other events, you can prevent the default behaviour - here, following the link to jquery.com - by calling event.preventDefault() in the event handler

If you want to preventDefault() only if a certain condition is fulfilled (something is hidden for instance), you could test the visibility of your ul with the class expanded. If it is visible (i.e. not hidden) the link should fire as normal, as the if statement will not be entered, and thus the default behaviour will not be prevented:

$('ul li').click(function(e) {
    if($('ul.expanded').is(':hidden')) {
        e.preventDefault();
        $('ul').addClass('expanded');
        $('ul.expanded').fadeIn(300);
    } 
});
karim79
  • 326,960
  • 63
  • 404
  • 402
  • 3
    With jQuery 1.7+ you can use on/off: http://stackoverflow.com/questions/209029/best-way-to-remove-an-event-handler-in-jquery – Lance Cleveland Jan 06 '12 at 18:05
  • if it has an href and onclick this will work $("#myLink").attr('onclick', '').click(function (e) { e.preventDefault(); }); – Ronald McDonald Dec 19 '12 at 21:58
  • realized through ajax and jquery I can hide a href buy having the callback to keep scrapers from getting these links. Awesome thanks! – Cesar Bielich Jul 07 '15 at 16:49
  • [this](http://stackoverflow.com/a/17935158/2218697) post has **easiest way using bootstrap**, hope helps. – Shaiju T Oct 15 '16 at 16:25
113

Try this:

$("a").removeAttr('href');

EDIT-

From your updated code:

 var location= $('#link1').attr("href");
 $("#link1").removeAttr('href');
 $('ul').addClass('expanded');
 $('ul.expanded').fadeIn(300);
 $("#link1").attr("href", location);
TStamper
  • 28,864
  • 10
  • 63
  • 72
  • 3
    Playing with href is very nice because is a fast way of disabiling a link which does action via a onclick event. Very very Clever! – daitangio Nov 18 '11 at 13:39
  • sweet method to keep the browser from adding the # within the URI when doing `href="#"` – Abela Feb 29 '16 at 11:00
66

For others who came here via google like me - here's another approach:

css:
.disabled {
  color: grey; // ...whatever
}

jQuery:
$('#myLink').click(function (e) {
  e.preventDefault();
  if ($(this).hasClass('disabled'))
    return false; // Do something else in here if required
  else
    window.location.href = $(this).attr('href');
});

// Elsewhere in your code
if (disabledCondition == true)
  $('#myLink').addClass('disabled')
else
  $('#myLink').removeClass('disabled')

Remember: not only this is a css class

class="buttonstyle"

but also these two

class="buttonstyle disabled"

so you can easily add and remove further classes with jQuery. No need to touch href...

I love jQuery! ;-)

Hein
  • 862
  • 8
  • 12
  • 2
    this assumes that the link has no target :) – dstarh Oct 16 '12 at 14:15
  • 2
    Instead of doing all of this fancyness, why not just tack the onclick higher in the dom, use `on()` to filter all `a.disabled` links and prevent default. Then all you have to do is toggle the disabled class on/off and the link will handle itself when "enabled". – CodeChimp Feb 27 '14 at 15:37
  • No need for the "== true" -- addClass('disabled') will run regardless. `if(disabledCondition)` – Tris - archived May 01 '14 at 13:53
  • 1
    @fwilson, while you're totally correct, for a beginning programmer, it is easier to understand with the ``== true``. :) – carmenism Sep 30 '14 at 19:21
  • Any particular reason not to simplify it to `if ($(this).hasClass('disabled')) { e.preventDefault(); }`? – Mir May 27 '19 at 20:05
58

Here is an alternate css/jQuery solution that I prefer for its terseness and minimized scripting:

css:

a.disabled {
  opacity: 0.5;
  pointer-events: none;
  cursor: default;
}

jQuery:

$('.disableAfterClick').click(function (e) {
   $(this).addClass('disabled');
});
Luca Fagioli
  • 10,385
  • 5
  • 46
  • 44
Peter DeWeese
  • 17,664
  • 8
  • 75
  • 98
  • 7
    [From Mozilla](https://developer.mozilla.org/en/CSS/pointer-events): "Warning: The use of pointer-events in CSS for non-SVG elements is experimental. The feature used to be part of the CSS3 UI draft specification but, due to many open issues, has been postponed to CSS4." – duelin markers Mar 29 '12 at 19:12
  • 1
    Thats a good consideration, but it happens to work well in most of the modern browsers. – Peter DeWeese Mar 30 '12 at 01:42
  • You might want to consider chaining `.prop("tabindex", "-1");` after the `addClass` – Oleg Grishko Jul 22 '19 at 13:22
19

You can remove click for link by following;

$('#link-id').unbind('click');

You can re-enable link by followings,

$('#link-id').bind('click');

You can not use 'disabled' property for links.

Kailas Mane
  • 1,727
  • 1
  • 14
  • 12
  • 1
    Easy to toggle on and off compared to others. – python1981 Apr 15 '15 at 02:23
  • 3
    "You can not use 'disabled' property for links." Wonder why there is no consistency between a button, and a link for disabling. "disabled" should work for a link too. It's like saying for a Chevy car you must hit the brake pedal to stop, but for this other car manufacturer, you must use this lever located on the roof. – eaglei22 Feb 02 '17 at 17:30
15

If you go the href route, you can save it

To disable:

$('a').each(function(){
    $(this).data("href", $(this).attr("href")).removeAttr("href");
});

Then re-enable using:

$('a').each(function(){
    $(this).attr("href", $(this).data("href"));
});

In one case I had to do it this way because the click events were already bound somewhere else and I had no control over it.

jBelanger
  • 1,145
  • 13
  • 9
12

I always use this in jQuery for disabling links

$("form a").attr("disabled", "disabled");
matox
  • 549
  • 6
  • 22
9

html link example:

        <!-- boostrap button + fontawesome icon -->
        <a class="btn btn-primary" id="BT_Download" target="_blank" href="DownloadDoc?Id=32">
        <i class="icon-file-text icon-large"></i>
        Download Document
        </a>

use this in jQuery

    $('#BT_Download').attr('disabled',true);

add this to css :

    a[disabled="disabled"] {
        pointer-events: none;
    }
Ch'nycos
  • 139
  • 1
  • 7
  • 1
    I'd never come across this CSS property before but this, for me, is by far the simplest method for disabling a hyperlink. The beauty of it is that when you remove the class which contains the `pointer-events: none` property from the anchor elements they revert to doing whatever they did previously when clicked. So if they were basic hyperlinks, they revert to navigating to the URL in their `href` attribute, and if they have a click event handler set, that becomes active again. Much simpler than saving `href` values and click handlers. – Philip Stratford Sep 13 '18 at 15:24
  • I like this solution, it is the simplest one. – louis Aug 20 '19 at 10:03
  • Out of a handful of "solutions" when nothing worked (and almost giving up this route), came to this **gem**. It's a no-fuss solution. And the only one which REALLY WORKS. Kudos. – user12379095 Apr 13 '20 at 17:29
  • awesome just brilliant – Nuno Sarmento Sep 17 '20 at 15:27
5

My fav in "checkout to edit an item and prevent -wild wild west clicks to anywhere- while in a checkout" functions

$('a').click(function(e) {
    var = $(this).attr('disabled');
    if (var === 'disabled') {
        e.preventDefault();
    }
});

So if i want that all external links in a second action toolbar should be disabled while in the "edit-mode" as described above, i'll add in the edit function

$('#actionToolbar .external').attr('disabled', true);

Link example after fire:

<a href="http://goo.gl" target="elsewhere" class="external" disabled="disabled">Google</a>

And now you CAN use disabled property for links

Cheers!

Lahmizzar
  • 469
  • 5
  • 6
3

You should find you answer here.

Thanks @Will and @Matt for this elegant solution.

jQuery('#path .to .your a').each(function(){
    var $t = jQuery(this);
    $t.after($t.text());
    $t.remove();
});
Community
  • 1
  • 1
warmth
  • 457
  • 6
  • 10
3

you can just hide and show the link as you like

$(link).hide();
$(link).show();
David Fawzy
  • 926
  • 11
  • 16
3

Just trigger stuff, set some flag, return false. If flag is set - do nothing.

Michał Chaniewski
  • 4,294
  • 1
  • 15
  • 15
  • Have tried that by setting a class, then calling that class later but return false carries through, and prevents the link from being called. – davebowker Jun 09 '09 at 14:34
2

unbind() was deprecated in jQuery 3, use the off() method instead:

$("a").off("click");
shintaroid
  • 1,276
  • 2
  • 14
  • 29
1

I know this isn't with jQuery but you can disable a link with some simple css:

a[disabled] {
  z-index: -1;
}

the HTML would look like

<a disabled="disabled" href="/start">Take Survey</a>
Cruz Nunez
  • 2,430
  • 1
  • 19
  • 30
0

This works for links that have the onclick attribute set inline. This also allows you to later remove the "return false" in order to enable it.

        //disable all links matching class
        $('.yourLinkClass').each(function(index) {
            var link = $(this);
            var OnClickValue = link.attr("onclick");
            link.attr("onclick", "return false; " + OnClickValue);
        });

        //enable all edit links
        $('.yourLinkClass').each(function (index) {
            var link = $(this);
            var OnClickValue = link.attr("onclick");
            link.attr("onclick", OnClickValue.replace("return false; ", ""));
        });
mga911
  • 1,536
  • 1
  • 16
  • 33
0

Just set preventDefault and return false

   $('#your-identifier').click(function(e) {
        e.preventDefault();
        return false;
    });

This will be disabled link but still, you will see a clickable icon(hand) icon. You can remove that too with below

$('#your-identifier').css('cursor', 'auto');
Rokan Nashp
  • 181
  • 2
  • 11
-2

Just use $("a").prop("disabled", true);. This will really disable de link element. Needs to be prop("disabled", true). Don't use attr("disabled", true)