DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

Cover image for Keep focus on an input with jQuery
Adam K Dean
Adam K Dean

Posted on

Keep focus on an input with jQuery

The most hair-loss-inducing problems usually have the simplest solutions, and such can be said for my latest shortcut to male pattern baldness.

I'm working on my forever project, and part of it requires that an input keep focus all of the time. User experience out of the window, this is the way it has to be, but .blur() is not cancel-able, nor is .focusout(). This means you can't just call .focus() in the .blur() function. You have to trick it.

Set initial focus first:

$("#input").focus();
Enter fullscreen mode Exit fullscreen mode

And then set the re-focus:

$("#input").blur(function() {
    setTimeout(function() { $("#input").focus(); }, 0);
});
Enter fullscreen mode Exit fullscreen mode

Works a treat.

Top comments (2)

Collapse
celsodesa profile image
Celso de Sรก


$("#input").focusout(()=> {
if($("#input").val() != ""){
$("#input").focus();
}
});

But it will prevent other inputs from being typed in.

Collapse
shrewmouse1 profile image
shrewmouse1

That's the whole point

DEV runs on 100% open source code known as Forem.

ย 
Contribute to the codebase or host your own.
ย 
Check these out! ๐Ÿ‘‡