How to keep the Focus on one textbox ? even if you click anywhere in a browser.
$("#txtSearch").focus();
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);
});
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
$("html").click(function(){
$("#txtSearch").focus();
});
Live Demo: http://jsfiddle.net/QhaLY/
It's also possible without jQuery and without re-focusing, if you just need a click on specific elements to not grab the focus
just listen for the mousedown event and cancel it
element.addEventListener("mousedown", event => {event.preventDefault(); event.stopPropagation()});
There are other ways of loosing focus than clicking area away from the input i.e. tabbing. If you want to prevent loosing focus use blur event i.e.
document.getElementById('txtSearch').addEventListener('blur', e => {
e.target.focus();
});