Zerium
Zerium

Reputation: 17333

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

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.

Upvotes: 35

Views: 51403

Answers (5)

UNK30WN
UNK30WN

Reputation: 64

Try using tabindex="-1" on button, maybe that'll work.

<input type="text" name="body" id="body" Placeholder="message..">
<input type="submit" value="send" id="sendButton" tabindex="-1">

Upvotes: 0

Thomas Deutsch
Thomas Deutsch

Reputation: 2544

Handle the mousedown-event instead of the click-event. The mousedown event will be handled before the focus of another element is lost.

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

e.preventDefault(); // in your mousedown eventhandler

JS-Fiddle demo

Upvotes: 79

jfriend00
jfriend00

Reputation: 707258

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

Upvotes: 8

Tmthetom
Tmthetom

Reputation: 79

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>

Upvotes: 1

Shiv Kumar Ganesh
Shiv Kumar Ganesh

Reputation: 3825

You can easily do this by applying focus back to the text area programmatically as the button click function is over. This way you can regain the focus along with the click event each time.

Upvotes: 0

Related Questions