Reputation: 10920
Suppose I have a page where a button or an input field is the most important element on the page. I know that I can automatically focus the element when the page loads by using the autofocus
attribute:
<button autofocus>Hello!</button>
This works as advertised, but unfortunately, the HTML element will lose focus if the user clicks on any other part of the page.
How can I permanently focus a HTML element?
(Note: if JavaScript really needs to be used to accomplish this task, please show the solution using plain JavaScript [i.e. without jQuery]).
EDIT: I am making a personal application where there is only ever going to be one button on the page, and nothing else. The focus will allow me to quickly "press" the button using the keyboard (e.g. by pressing the enter key) at any time.
Upvotes: 3
Views: 2302
Reputation: 1074198
Please see my comment. I'd strongly recommend not doing this in the general case, but yours sounds like quite a specific case in a well-controlled environment.
You can hook the blur
event on the button and try to give it focus again:
document.querySelector("button[autofocus]").addEventListener("blur", function() {
var t = this;
t.focus();
setTimeout(function() { // Some browsers won't let you do it until
t.focus(); // after the blur has completed
}, 100);
});
<button autofocus>This is the button</button>
<button>Another button</button> just so we can see that it works if we tab away from the first one.
Or use an interval timer, etc.
Upvotes: 4
Reputation: 61063
Heed the warnings in the comments.
document.getElementById('stayHere').addEventListener('blur', function() {
this.focus();
});
You could potentially do this with CSS to some extent, also:
body {
pointer-events: none;
}
.greedy-button {
pointer-events: auto;
}
Upvotes: 1
Reputation: 66488
I think the only option is JavaScript like this:
var button = document.querySelector('button');
document.addEventListener('click', function(e) {
if(!e.target.matches('button[autofocus]')) {
button.focus();
}
})
<button autofocus>focus</button>
Upvotes: 0