How to make element not lose focus when button is pressed?

31,754

Solution 1

There is no need to renew the focus!

Make sure you handle the mousedown event (instead of the click-event). The mousedown event will fire before the focus of another element is lost.

In your mousedown event handler, you need to to prevent event default behavior.

e.preventDefault(); // on your mousedown event

JS-Fiddle demo

Solution 2

You can't stop the focus from moving to a focusable element and still allow the mouse click to have its normal behavior (such as click the button). If you click on an element that supports focus such as a button, it will get the keyboard focus.

It is possible to programmatically put focus back on an element if done properly. If done poorly, it can ruin the usability of a page.

Demo: JSFiddle

Solution 3

You have to renew focus when button is pressed.

HTML code:

<input id="messageBox" autofocus />
<input type="button" id="messageSend" onclick="setFocusToMessageBox()" value="Send" />

Javascript code:

<script>
function setFocusToMessageBox(){
    document.getElementById("messageBox").focus();
}
</script>
Share:
31,754
Lucas
Author by

Lucas

Updated on July 09, 2022

Comments

  • Lucas
    Lucas almost 2 years

    I have a textarea in which I am inserting content at the location of the caret (thanks to Tim Down's answer). It inserts the content when the user presses a button. But it seems that when the button is pressed, the focus on the textarea is lost. How do I keep the focus there, providing the location of the caret is also the same? I was thinking along the lines of using evt.preventDefault() with .focusout(). If that helps.