Trigger click event on keypress for any focused element
If the elements on your page already have click events, and are in the tab order, and you just want to make the enter key trigger a click on whichever element has focus for accessibility, try the following:
<head>
<script>
function handleEnter(e){
var keycode = (e.keyCode ? e.keyCode : e.which);
if (keycode == '13') {
document.activeElement.click();
}
}
</script>
</head>
<body onkeypress="handleEnter(event)">
This is especially useful for adding play/pause and making other image based controls accessible in banner ads made with Google Web Designer.
Is there a default way to trigger a click event anytime enter is pressed on a focused element?
There's no solution without javascript.
Although the onclick
has a special behavior as the W3C mentions
While "onclick" sounds like it is tied to the mouse, the onclick event is actually mapped to the default action of a link or button.
this does not work with other elements than links and buttons.
You could be tempted to add role="button"
to a div
with a tabindex="0"
. This does not work.
The Mozilla documentation explicitely says that you have to define handler, even with the button
role.
This is easily understandable as this is a browser feature. When you define role=link
on an element, you can't right click on it, hoping that it will open your browser context menu. For the same reason, defining the role=button
attribute won't affect the default behavior. From this discussion:
ARIA simply conveys the accessibility semantics intended by the author that are conveyed to an assistive technology.
Also do not forget to handle the space key. Read Karl Groves article and example about the subject.