Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent an element from losing focus?

Tags:

How to keep the Focus on one textbox ? even if you click anywhere in a browser.

$("#txtSearch").focus(); 
like image 429
Ibonesh Avatar asked Apr 16 '13 13:04

Ibonesh


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

Which method is triggered when an element loses focus?

The focusout() method attaches a function to run when a focusout event occurs on the element, or any elements inside it. Unlike the blur() method, the focusout() method also triggers if any child elements lose focus.

How do you add focus to an element?

To set focus to an HTML form element, the focus() method of JavaScript can be used. To do so, call this method on an object of the element that is to be focused, as shown in the example. Example 1: The focus() method is set to the input tag when user clicks on Focus button.

What element can be focused?

The only standard we have is DOM Level 2 HTML, according to which the only elements that have a focus() method are HTMLInputElement , HTMLSelectElement , HTMLTextAreaElement and HTMLAnchorElement . This notably omits HTMLButtonElement and HTMLAreaElement .


2 Answers

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

This way you don't rely on subscribing to the events of any other element on the page. If you subscribe to body click or html click, it won't run if any other element prevents propagation of its click event, also it won't work when tabbing out of the textbox.

Example:

<!-- I will not propagate my click to top level DOM elements --> <button id="button">Click me</button>  <script> $('#button').click(function (event) {     event.stopPropagation(); }); </script> 
like image 151
Konstantin Dinev Avatar answered Sep 22 '22 07:09

Konstantin Dinev


Konstantin Dinev answer works ok in most cases, but if you dont want to lose the focus only when clicking on certain parts of the html just do this:

$(".nofocus").on( "mousedown", function (e) {     return false; }); 

In my case i'm doing a small html text editor and i dont want to lose the control when pressing an action button, but yes in any other case.

I just need to add the nofocus class to the button and it will not take the control

like image 24
hamboy75 Avatar answered Sep 25 '22 07:09

hamboy75