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.
You need to subscribe to the blur event of the textbox and reinstate focus with a small timeout: $('#txtSearch'). blur(function (event) { setTimeout(function () { $("#txtSearch"). focus(); }, 20); });
The focusout event fires when an element is about to lose focus. The main difference between this event and blur is that focusout bubbles while blur does not.
To remove focus around the button outline:none property is used. Outline property: Outline is an element property which draws a line around element but outside the border. It does not take space from the width of an element like border.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With