Home > Software engineering >  How to move focus from button to another button
How to move focus from button to another button

Time:03-19

I tried to focus or trigger but it's not working. Please let me know if you have any knowledge. Thanks in advance!

<button onclick="myFunction()">Click</button>
<button id="close-btn">Focus Button</button>


function myFunction() {
   let closeBtn = document.getElementById('close-btn');
       closeBtn.focus();
}

CodePudding user response:

This may solve your problem, the css part is just to show the effect.

document.querySelector('#open-btn').addEventListener('click', ()=>{
  document.querySelector('#close-btn').focus()
})
button:focus {
    border: 2px solid rgb(54, 13, 13);
    background-color: aquamarine;
}
<!DOCTYPE HTML>
<html>

<body>
      <button id="open-btn">Click</button>
      <button id="close-btn">Focus Button</button>
</body>

</html>

CodePudding user response:

Try using function(e) { e.preventDefault(); ..... }

This will prevent browser's default behaviour of any element.

Thanks!

  • Related