Nomensa has a good article on their blog about Keyboard Traps, or “I don’t use a mouse and the Javascript on a web page is stopping me tabbing past an item.”
Here’s the theory. If you use Javascript events and code to override the normal keyboard operation on something like a link or button then you have to check that you can still use the page with the tab, return, space and cursor keys. If you’ve blocked this, for whatever reason, your page will no longer be usable/accessible for keyboard users – screenreader or switch users, for example.
The example given in the Nomensa article, however, is an odd one. It traps not clicks but keyboard activity. So it’s a link that would open a pop-up window if you pressed a key while it had focus, and uses the Javascript preventDefault
statement to terminate the key activity, blocking the tab to get to a new link.
But mouse users would not see any effect. This means it’s unlikely that this scenario will ever be coded: mouse users are generally the target audience, so the scenario is usually going to be “clicks are trapped and do something different” not “keyboard activity is trapped and does something different.”
Here’s an example: the Firefox development test for preventDefault
. You can activate the blocking of normal mouse operation on the test checkbox, so you can no longer click on it to check or uncheck it. But using a keyboard you can tab past it and even check it! The development test assumes you trap the mouse click event, not keyboard events.
This suggests that the accessibility problem with preventDefault
won’t usually be the creation of keyboard traps.
The accessibility problem preventDefault
is that it will be used to create webpages where a keyboard user gets different functionality from a mouse user.
Most likely, this means that webpages that use preventDefault
in trapped click events won’t work properly for keyboard users – for example, when you activate a link with the keyboard instead of the mouse, then instead of operating some code somewhere on the page to make a hidden piece of text visible, you trigger a navigation action.
And look, here’s an example of exactly that problem from stackoverflow: preventDefault() on an <a> tag Mouse users get to see text appear and disappear as they click. Keyboard users just get a click as the browser navigates to the page again.
What to recommend? If you must use events and preventDefault
then trap both mouse and keyboard events, but make sure you don’t trap tab or cursor key presses or you’ll break keyboard users.
But better still, don’t use Javascript to break the default activity of a webpage element. If you want something you click and does something use a button, not a link!