Bonesh
Bonesh

Reputation: 837

How to prevent an element from losing focus?

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

$("#txtSearch").focus();

Upvotes: 28

Views: 43749

Answers (7)

Stroga
Stroga

Reputation: 1

I use onMouseDown={e => e.preventDefault()} and that works just fine.

Upvotes: 0

Hamboy75
Hamboy75

Reputation: 1079

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

Upvotes: 9

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

Upvotes: 4

Alan Bogu
Alan Bogu

Reputation: 775

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

Upvotes: 0

Konstantin Dinev
Konstantin Dinev

Reputation: 34895

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>

Upvotes: 33

user1032531
user1032531

Reputation: 26281

$('body').click(function(){$("#txtSearch").focus();});

Upvotes: 1

Curtis
Curtis

Reputation: 103358

$("html").click(function(){
   $("#txtSearch").focus();
});

Live Demo: http://jsfiddle.net/QhaLY/

Upvotes: 3

Related Questions