Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Focus method triggers button click event

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>
like image 850
Madhan Avatar asked Sep 01 '25 22:09

Madhan


1 Answers

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>
like image 98
Barmar Avatar answered Sep 03 '25 10:09

Barmar