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();
}
});
To trigger a click button on ENTER key, We can use any of the keyup(), keydown() and keypress() events of jQuery. keyup(): This event occurs when a keyboard key is released. The method either triggers the keyup event, or to run a function when a keyup event occurs.
Given an HTML document containing text area and the task is to trigger the button when the user hit Enter button. We can do it by using “keyup”, “keydown”, or “keypress” event listener on textbox depending on the need.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With