How to keep the Focus on one textbox ? even if you click anywhere in a browser.
$("#txtSearch").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); });
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.
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.
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 .
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>
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
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