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.
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
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
unselectable="on"
also seems to work, for buttons at least. –
Beggs .preventDefault()
in mousedown: jsfiddle.net/Ddffh/103 . On click just happens to be too late because after mousedown, focus has already been lost. You can verify this in your own demo by holding the mouse button down for a bit before releasing: when you first mousedown, focus will be lost; after you release, the click event fires. –
Roobbie 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.
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">
© 2022 - 2024 — McMap. All rights reserved.