jQuery disable a link
Asked Answered
G

18

308

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;
});
Glick answered 9/6, 2009 at 14:27 Comment(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").Baresark
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?Secondary
Otherwise, can you explain why you are taking this approach as a better understanding of the problem space will improve the answers.Secondary
@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.Glick
@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.Glick
@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.Heaveho
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.Mammalogy
H
377
$('#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);
    } 
});
Hagood answered 9/6, 2009 at 14:33 Comment(5)
With jQuery 1.7+ you can use on/off: #209529Galiot
if it has an href and onclick this will work $("#myLink").attr('onclick', '').click(function (e) { e.preventDefault(); });Onshore
realized through ajax and jquery I can hide a href buy having the callback to keep scrapers from getting these links. Awesome thanks!Whatnot
this post has easiest way using bootstrap, hope helps.Turbinal
@LanceCleveland The solution you linked to does not work for anchor tags.Inexplicit
P
118

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);
Pneumato answered 9/6, 2009 at 14:35 Comment(2)
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!Acaroid
sweet method to keep the browser from adding the # within the URI when doing href="#"Antirachitic
G
70

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! ;-)

Gey answered 12/9, 2011 at 14:20 Comment(5)
this assumes that the link has no target :)Liquescent
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".Vesperal
No need for the "== true" -- addClass('disabled') will run regardless. if(disabledCondition)Kraut
@fwilson, while you're totally correct, for a beginning programmer, it is easier to understand with the == true. :)Cunnilingus
Any particular reason not to simplify it to if ($(this).hasClass('disabled')) { e.preventDefault(); }?Adapter
T
64

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');
});
Trainer answered 29/2, 2012 at 19:15 Comment(3)
From Mozilla: "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."Demonstrable
Thats a good consideration, but it happens to work well in most of the modern browsers.Trainer
You might want to consider chaining .prop("tabindex", "-1"); after the addClassEssary
B
22

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.

Birefringence answered 12/6, 2013 at 6:34 Comment(3)
Easy to toggle on and off compared to others.Imperceptible
"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.Sopping
As of jQuery 3.0, .unbind() has been deprecated. It was superseded by the .off() method since jQuery 1.7. Docs: api.jquery.com/unbindGleeson
D
16

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.

Diuresis answered 8/5, 2014 at 14:27 Comment(0)
C
14

I always use this in jQuery for disabling links

$("form a").attr("disabled", "disabled");
Caleb answered 26/2, 2014 at 10:27 Comment(1)
You also can use $("form a").attr("disabled", false); to make it enabled againPalinode
S
12

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;
    }
Simpleminded answered 9/9, 2018 at 9:26 Comment(4)
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.Idell
I like this solution, it is the simplest one.Bearskin
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.Firebird
awesome just brilliantHenriettahenriette
L
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!

Ligure answered 4/7, 2013 at 3:44 Comment(0)
I
4

you can just hide and show the link as you like

$(link).hide();
$(link).show();
Imbricate answered 13/1, 2016 at 9:53 Comment(1)
you can it's just not great ux though.Maiga
H
3

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

Hedgehog answered 9/6, 2009 at 14:30 Comment(1)
Have tried that by setting a class, then calling that class later but return false carries through, and prevents the link from being called.Glick
M
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();
});
Magistral answered 27/11, 2012 at 16:13 Comment(0)
J
2

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

$("a").off("click");
Jointworm answered 30/5, 2018 at 9:43 Comment(0)
N
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>
Notice answered 28/6, 2016 at 19:37 Comment(0)
S
1

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');
Sharpwitted answered 24/7, 2020 at 12:5 Comment(0)
S
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; ", ""));
        });
Stroh answered 6/4, 2018 at 4:44 Comment(0)
M
0

As a back-end engineer, it took me a while to wrap my head around how to do this but here is how i solved the exact same problem.

const resendCodeTimeOutPeriodInMs = 30000; // 30seconds.

function resend2faCodeOnLogin(sendByEmail) {

const resendCodeLinkElement = $('#resendCodeLink');

const disabledState = resendCodeLinkElement.attr('disabled');
if (disabledState === 'disabled') {
    resendCodeLinkElement.preventDefault();
} else {
    resendCodeLinkElement.attr("disabled", true);
    resendCodeLinkElement.addClass('disabled');

    submitForm('#twoFactorResendCodeForm', (response) => {
        setTimeout(function () {
            $('#resendCodeLink').removeClass('disabled');
            resendCodeLinkElement.attr("disabled", false);
        }, resendCodeTimeOutPeriodInMs); 

    }, (response) => {
        console.error(response);
    });
}
}

Standard CSS taken from well known examples off the web:

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

My Approach was to ensure a given button is disabled for 30s before the UX can click it again.

Maiga answered 10/2, 2022 at 14:46 Comment(0)
C
-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)

Coleorhiza answered 8/3, 2018 at 17:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.