Reputation: 430
Is there a default way to trigger a click event anytime enter is pressed on a focused element?
What I am referencing is the differences from pressing enter while focused on a <button>
vs. pressing enter while focused on a <div> <li> <span>
, etc. The <button>
keypress enter
triggers as expected. However, <div>
keypress enter
does nothing. I believe you have to specifically write the event in for that keypress.
$('li').click(function() {
//toggles something
});
$("li").keydown(function(e){
if(e.which === 13){
$(this).click();
}
});
Upvotes: 17
Views: 33327
Reputation: 18807
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.
Upvotes: 20
Reputation: 91
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.
Upvotes: 9
Reputation: 1521
Certain HTML Elements such as span, li, div
doesn't not have really have a focused state hence the focus won't trigger. What can be done in order to give the element a possible focus state is to add a tabindex and it will work, e.g:
<div tabindex="0"></div>
Upvotes: 0
Reputation: 17485
When I listen for keyboard events on a list, I put the handler on the <ul>
instead of the <li>
and it works great. It might work on the <li>
as well but your example above sounds like it doesn't.
Upvotes: -1