Skip to content

Instantly share code, notes, and snippets.

@rosskevin
Created October 16, 2014 20:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rosskevin/fa3c6180102cfa75df63 to your computer and use it in GitHub Desktop.
Save rosskevin/fa3c6180102cfa75df63 to your computer and use it in GitHub Desktop.
AnchorDisabler.coffee - disable links once and for all with a.disabled or the disabled attribute
class AnchorDisabler
###
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()
###
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
@maxpen
Copy link

maxpen commented Feb 13, 2016

how would I translate this in vanilla javascript?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment