i have a div with keydown handler and button with click handler, in that keydown handler i am focusing a button with focus() method, but it triggers btn click handler. please tell why this happens
Note: press enter key on div
function btnclick() {
console.log('button click triggered');
}
function btnKeyDown() {
console.log('key down triggered');
document.getElementById('btn1').focus();
}
<div id='btn' onkeydown="btnKeyDown()" tabindex='0'>Click1</div>
<button id='btn1' onclick="btnclick()">Click Me!2</button>
This strange behavior only happens when you press the Return key. Pressing Return while focus is on an element is equivalent to clicking on it. So when you change the focus, the default action is performed on the newly focused element, not the original one.
Calling event.preventDefault()
prevents this from happening.
function btnclick() {
console.log('button click triggered');
}
function btnKeyDown(event) {
console.log('key down triggered');
document.getElementById('btn1').focus();
event.preventDefault();
}
<div id='btn' onkeydown="btnKeyDown(event)" tabindex='0'>Click1</div>
<button id='btn1' onclick="btnclick()">Click Me!2</button>
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