Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 760
Lucas Avatar asked Aug 28 '12 07:08

Lucas


People also ask

How can you prevent elements from losing focus?

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); });

What event tells when an element loses focus?

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.

How do I remove button focus on click?

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.


2 Answers

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

like image 149
Thomas Deutsch Avatar answered Sep 23 '22 22:09

Thomas Deutsch


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

like image 29
jfriend00 Avatar answered Sep 21 '22 22:09

jfriend00