简体   繁体   中英

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.

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

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

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM