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

Lucas picture Lucas · Aug 28, 2012 · Viewed 24.1k times · Source

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.

Answer

Thomas Deutsch picture Thomas Deutsch · Apr 26, 2017

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