Is there any way to disable a link using CSS?
I have a class called current-page
and want links with this class to be disabled so that no action occurs
Thanks to everyone that posted solutions, I combined multiple approaches to provide some more advanced disabled
functionality. Here is a gist, and the code is below.
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
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 such as (with optional selector):
$ ->
new AnchorDisabler()
Here is the 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
If you want to stick to just HTML/CSS on a form, another option is to use a button. Style it and set the disabled
attribute.
E.g. http://jsfiddle.net/cFTxH/1/
The answer is already in the comments of the question. For more visibility, I am copying this solution here:
.not-active {
pointer-events: none;
cursor: default;
text-decoration: none;
color: black;
}
<a href="link.html" class="not-active">Link</a>
For browser support, please see https://caniuse.com/#feat=pointer-events. If you need to support IE there is a workaround; see this answer.
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.
.disabled {
pointer-events: none;
cursor: default;
opacity: 0.6;
}
<a href="#" class="disabled">link</a>