How to disable HTML links

JavascriptJqueryHtmlCss

Javascript Problem Overview


I have a link button inside a <td> which I have to disable. This works on IE but not working in Firefox and Chrome. Structure is - Link inside a <td>. I cannot add any container in the <td> (like div/span)

I tried all the following but not working on Firefox (using 1.4.2 js):

$(td).children().each(function () {
        $(this).attr('disabled', 'disabled');
  });


  $(td).children().attr('disabled', 'disabled');

  $(td).children().attr('disabled', true);

  $(td).children().attr('disabled', 'true');

Note - I cannot de-register the click function for the anchor tag as it is registered dynamically. AND I HAVE TO SHOW THE LINK IN DISABLED MODE.

Javascript Solutions


Solution 1 - Javascript

You can't disable a link (in a portable way). You can use one of these techniques (each one with its own benefits and disadvantages).

CSS way

This should be the right way (but see later) to do it when most of browsers will support it:

a.disabled {
    pointer-events: none;
}

It's what, for example, Bootstrap 3.x does. Currently (2016) it's well supported only by Chrome, FireFox and Opera (19+). Internet Explorer started to support this from version 11 but not for links however it's available in an outer element like:

span.disable-links {
    pointer-events: none;
}

With:

<span class="disable-links"><a href="#">...</a></span>

Workaround

We, probably, need to define a CSS class for pointer-events: none but what if we reuse the disabled attribute instead of a CSS class? Strictly speaking disabled is not supported for <a> but browsers won't complain for unknown attributes. Using the disabled attribute IE will ignore pointer-events but it will honor IE specific disabled attribute; other CSS compliant browsers will ignore unknown disabled attribute and honor pointer-events. Easier to write than to explain:

a[disabled] {
    pointer-events: none;
}

Another option for IE 11 is to set display of link elements to block or inline-block:

<a style="pointer-events: none; display: inline-block;" href="#">...</a>

Note that this may be a portable solution if you need to support IE (and you can change your HTML) but...

All this said please note that pointer-events disables only...pointer events. Links will still be navigable through keyboard then you also need to apply one of the other techniques described here.

Focus

In conjunction with above described CSS technique you may use tabindex in a non-standard way to prevent an element to be focused:

<a href="#" disabled tabindex="-1">...</a>

I never checked its compatibility with many browsers then you may want to test it by yourself before using this. It has the advantage to work without JavaScript. Unfortunately (but obviously) tabindex cannot be changed from CSS.

Intercept clicks

Use a href to a JavaScript function, check for the condition (or the disabled attribute itself) and do nothing in case.

$("td > a").on("click", function(event){
    if ($(this).is("[disabled]")) {
        event.preventDefault();
    }
});

To disable links do this:

$("td > a").attr("disabled", "disabled");

To re-enable them:

$("td > a").removeAttr("disabled");

If you want instead of .is("[disabled]") you may use .attr("disabled") != undefined (jQuery 1.6+ will always return undefined when the attribute is not set) but is() is much more clear (thanks to Dave Stewart for this tip). Please note here I'm using the disabled attribute in a non-standard way, if you care about this then replace attribute with a class and replace .is("[disabled]") with .hasClass("disabled") (adding and removing with addClass() and removeClass()).

Zoltán Tamási noted in a comment that "in some cases the click event is already bound to some "real" function (for example using knockoutjs) In that case the event handler ordering can cause some troubles. Hence I implemented disabled links by binding a return false handler to the link's touchstart, mousedown and keydown events. It has some drawbacks (it will prevent touch scrolling started on the link)" but handling keyboard events also has the benefit to prevent keyboard navigation.

Note that if href isn't cleared it's possible for the user to manually visit that page.

Clear the href attribute. With this code you do not add an event handler but you change the link itself. Use this code to disable links:

$("td > a").each(function() {
    this.data("href", this.attr("href"))
        .attr("href", "javascript:void(0)")
        .attr("disabled", "disabled");
});

And this one to re-enable them:

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

Personally I do not like this solution very much (if you do not have to do more with disabled links) but it may be more compatible because of various way to follow a link.

Fake click handler

Add/remove an onclick function where you return false, link won't be followed. To disable links:

$("td > a").attr("disabled", "disabled").on("click", function() {
    return false; 
});

To re-enable them:

$("td > a").removeAttr("disabled").off("click");

I do not think there is a reason to prefer this solution instead of the first one.

Styling

Styling is even more simple, whatever solution you're using to disable the link we did add a disabled attribute so you can use following CSS rule:

a[disabled] {
    color: gray;
}

If you're using a class instead of attribute:

a.disabled {
    color: gray;
}

If you're using an UI framework you may see that disabled links aren't styled properly. Bootstrap 3.x, for example, handles this scenario and button is correctly styled both with disabled attribute and with .disabled class. If, instead, you're clearing the link (or using one of the others JavaScript techniques) you must also handle styling because an <a> without href is still painted as enabled.

Accessible Rich Internet Applications (ARIA)

Do not forget to also include an attribute aria-disabled="true" together with disabled attribute/class.

Solution 2 - Javascript

Got the fix in css.

td.disabledAnchor a{
       pointer-events: none !important;
       cursor: default;
       color:Gray;
}

Above css when applied to the anchor tag will disable the click event.

For details checkout this link

Solution 3 - Javascript

Thanks to everyone that posted solutions (especially @AdrianoRepetti), I combined multiple approaches to provide some more advanced disabled functionality (and it works cross browser). The code is below (both ES2015 and coffeescript based on your preference).

This provides for multiple levels of defense so that Anchors marked as disable actually behave as such. Using this approach, you get an anchor that you cannot:

  • click
  • tab to and hit return
  • tabbing to it will move focus to the next focusable element
  • it is aware if the anchor is subsequently enabled

How to

  1. Include this css, as it is the first line of defense. This assumes the selector you use is a.disabled

    a.disabled {
      pointer-events: none;
      cursor: default;
    }
    
  2. Next, instantiate this class on ready (with optional selector):

       new AnchorDisabler()
    

ES2015 Class

npm install -S key.js

import {Key, Keycodes} from 'key.js'

export default class AnchorDisabler {
  constructor (config = { selector: 'a.disabled' }) {
    this.config = config
    $(this.config.selector)
      .click((ev) => this.onClick(ev))
      .keyup((ev) => this.onKeyup(ev))
      .focus((ev) => this.onFocus(ev))
  }

  isStillDisabled (ev) {
    //  since disabled can be a class or an attribute, and it can be dynamically removed, always recheck on a watched event
    let target = $(ev.target)
    if (target.hasClass('disabled') || target.prop('disabled') == 'disabled') {
      return true
    }
    else {
      return false
    }
  }

  onFocus (ev) {
    //  if an attempt is made to focus on a disabled element, just move it along to the next focusable one.
    if (!this.isStillDisabled(ev)) {
      return
    }

    let focusables = $(':focusable')
    if (!focusables) {
      return
    }

    let current = focusables.index(ev.target)
    let next = null
    if (focusables.eq(current + 1).length) {
      next = focusables.eq(current + 1)
    } else {
      next = focusables.eq(0)
    }

    if (next) {
      next.focus()
    }
  }

  onClick (ev) {
    // disabled could be dynamically removed
    if (!this.isStillDisabled(ev)) {
      return
    }

    ev.preventDefault()
    return false
  }

  onKeyup (ev) {
    // We are only interested in disabling Enter so get out fast
    if (Key.isNot(ev, Keycodes.ENTER)) {
      return
    }

    // disabled could be dynamically removed
    if (!this.isStillDisabled(ev)) {
      return
    }

    ev.preventDefault()
    return false
  }
}

Coffescript class:

class AnchorDisabler
  constructor: (selector = 'a.disabled') ->
    $(selector).click(@onClick).keyup(@onKeyup).focus(@onFocus)

  isStillDisabled: (ev) =>
    ### since disabled can be a class or an attribute, and it can be dynamically removed, always recheck on a watched event ###
    target = $(ev.target)
    return true if target.hasClass('disabled')
    return true if target.attr('disabled') is 'disabled'
    return false

  onFocus: (ev) =>
    ### if an attempt is made to focus on a disabled element, just move it along to the next focusable one. ###
    return unless @isStillDisabled(ev)

    focusables = $(':focusable')
    return unless focusables

    current = focusables.index(ev.target)
    next = (if focusables.eq(current + 1).length then focusables.eq(current + 1) else focusables.eq(0))

    next.focus() if next


  onClick: (ev) =>
    # disabled could be dynamically removed
    return unless @isStillDisabled(ev)

    ev.preventDefault()
    return false

  onKeyup: (ev) =>

    # 13 is the js key code for Enter, we are only interested in disabling that so get out fast
    code = ev.keyCode or ev.which
    return unless code is 13

    # disabled could be dynamically removed
    return unless @isStillDisabled(ev)

    ev.preventDefault()
    return false

Solution 4 - Javascript

Try the element:

$(td).find('a').attr('disabled', 'disabled');

Disabling a link works for me in Chrome: http://jsfiddle.net/KeesCBakker/LGYpz/.

Firefox doesn't seem to play nice. This example works:

<a id="a1" href="http://www.google.com">Google 1</a>
<a id="a2" href="http://www.google.com">Google 2</a>

$('#a1').attr('disabled', 'disabled');

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

Note: added a 'live' statement for future disabled / enabled links.
Note2: changed 'live' into 'on'.

Solution 5 - Javascript

Bootstrap 4.1 provides a class named disabled and aria-disabled="true" attribute.

example"

<a href="#" 
        class="btn btn-primary btn-lg disabled" 
        tabindex="-1" 
        role="button" aria-disabled="true"
>
    Primary link
</a>

More is on getbootstrap.com

So if you want to make it dynamically, and you don't want to care if it is button or ancor than in JS script you need something like that

   let $btn=$('.myClass');
   $btn.attr('disabled', true);
   if ($btn[0].tagName == 'A'){
        $btn.off();
        $btn.addClass('disabled');
        $btn.attr('aria-disabled', true);
   }

But be carefull

The solution only works on links with classes btn btn-link.

Sometimes bootstrap recommends using card-link class, in this case solution will not work.

Solution 6 - Javascript

I've ended up with the solution below, which can work with either an attribute, <a href="..." disabled="disabled">, or a class <a href="..." class="disabled">:

CSS Styles:

a[disabled=disabled], a.disabled {
	color: gray;
	cursor: default;
}

a[disabled=disabled]:hover, a.disabled:hover {
	text-decoration: none;
}

Javascript (in jQuery ready):

$("a[disabled], a.disabled").on("click", function(e){

	var $this = $(this);
	if ($this.is("[disabled=disabled]") || $this.hasClass("disabled"))
		e.preventDefault();
})

Solution 7 - Javascript

Just add a css property:

<style>   
a {
 pointer-events: none;
}
</style>

Doing so you can disable the anchor tag.

Solution 8 - Javascript

You can disable the HTML link as given below:

<style>
    .disabled-link {
        pointer-events: none;
    }
</style>
<a href="https://google.com" class="disabled-link">Google.com</a>

You can use inline JavaScript:

<a href="javascript:void(0)">Google.com</a>

Solution 9 - Javascript

you cannot disable a link, if you want that click event should not fire then simply Remove the action from that link.

$(td).find('a').attr('href', '');

For More Info :- Elements that can be Disabled

Solution 10 - Javascript

I would do something like

$('td').find('a').each(function(){
 $(this).addClass('disabled-link');
});

$('.disabled-link').on('click', false);

something like this should work. You add a class for links you want to have disabled and then you return false when someone click them. To enable them just remove the class.

Solution 11 - Javascript

To disable link to access another page on touch device:

if (control == false)
  document.getElementById('id_link').setAttribute('href', '#');
else
  document.getElementById('id_link').setAttribute('href', 'page/link.html');
end if;

Solution 12 - Javascript

In Razor (.cshtml) you can do:

@{
    var isDisabled = true;
}

<a href="@(isDisabled ? "#" : @Url.Action("Index", "Home"))" @(isDisabled ? "disabled=disabled" : "") class="btn btn-default btn-lg btn-block">Home</a>

Solution 13 - Javascript

I would suggest turning the link into a button and using the 'disabled' attribute. You can see this issue to check how to convert a link to a button: https://stackoverflow.com/questions/2906582/how-to-create-an-html-button-that-acts-like-a-link

Solution 14 - Javascript

You can use this to disabled the Hyperlink of asp.net or link buttons in html.

$("td > a").attr("disabled", "disabled").on("click", function() {
    return false; 
});

Solution 15 - Javascript

There is one other possible way, and the one that I like best. Basically it's the same way lightbox disables a whole page, by placing a div and fiddling with z-index. Here is relevant snippets from a project of mine. This works in all browsers!!!!!

Javascript (jQuery):

var windowResizer = function(){
		var offset = $('#back').offset();	
		var buttontop = offset.top;
		var buttonleft = offset.left;
		$('#backdisabler').css({'top':buttontop,'left':buttonleft,'visibility':'visible'});
		offset = $('#next').offset();
		buttontop = offset.top;
		buttonleft = offset.left;
		$('#nextdisabler').css({'top':buttontop,'left':buttonleft,'visibility':'visible'});
}

$(document).ready(function() {
	$(window).resize(function()	{   
		setTimeout(function() {
			windowResizer();
		}, 5); //when the maximize/restore buttons are pressed, we have to wait or it will fire to fast
	});
});

and in html

<a href="" id="back" style="float: left"><img src="images/icons/back.png" style="height: 50px; width: 50px" /></a>
<a href="" id="next" style="float: right"><img src="images/icons/next.png" style="height: 50px; width: 50px" /></a>
<img id="backdisabler" src="images/icons/disabled.png" style="visibility: hidden; position: absolute; padding: 5px; height: 62px; width: 62px; z-index: 9000"/>
<img id="nextdisabler" src="images/icons/disabled.png" style="visibility: hidden; position: absolute; padding: 5px; height: 62px; width: 62px; z-index: 9000"/>

So the resizer finds the anchor's (the images are just arrows) locations and places the disabler on top. The disabler's image is a translucent grey square (change the width/height of the disablers in the html to match your link) to show that it is disabled. The floating allows the page to resize dynamically, and the disablers will follow suit in windowResizer(). You can find suitable images through google. I have placed the relevant css inline for simplicity.

then based on some condition,

$('#backdisabler').css({'visibility':'hidden'});
$('#nextdisabler').css({'visibility':'visible'});

Solution 16 - Javascript

I think a lot of these are over thinking. Add a class of whatever you want, like disabled_link.
Then make the css have .disabled_link { display: none }
Boom now the user can't see the link so you won't have to worry about them clicking it. If they do something to satisfy the link being clickable, simply remove the class with jQuery:
$("a.disabled_link").removeClass("super_disabled"). Boom done!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnkitView Question on Stackoverflow
Solution 1 - JavascriptAdriano RepettiView Answer on Stackoverflow
Solution 2 - JavascriptAnkitView Answer on Stackoverflow
Solution 3 - JavascriptkrossView Answer on Stackoverflow
Solution 4 - JavascriptKees C. BakkerView Answer on Stackoverflow
Solution 5 - JavascriptYevgeniy AfanasyevView Answer on Stackoverflow
Solution 6 - JavascriptisapirView Answer on Stackoverflow
Solution 7 - JavascriptSourabh PotnisView Answer on Stackoverflow
Solution 8 - JavascriptHedayatullah SarwaryView Answer on Stackoverflow
Solution 9 - JavascriptPranavView Answer on Stackoverflow
Solution 10 - JavascriptmkkView Answer on Stackoverflow
Solution 11 - JavascriptrgfpyView Answer on Stackoverflow
Solution 12 - JavascriptJoel WiklundView Answer on Stackoverflow
Solution 13 - JavascriptvinkomlacicView Answer on Stackoverflow
Solution 14 - JavascriptMiteshView Answer on Stackoverflow
Solution 15 - JavascriptJon CrawfordView Answer on Stackoverflow
Solution 16 - JavascriptJordan Michael RushingView Answer on Stackoverflow