Is there any way to set focus to the document, i.e. the content area, in JavaScript? document.focus()
doesn’t seem to do anything.
Is there any way in JavaScript to focus the document (content area)?
Asked Answered
In HTML 4.01, focus is only discussed in the context of elements such as form controls and links. In HTML 5, it is discussed much more widely. However, how focus works for documents is mostly browser dependent.
You might try:
// Give the document focus
window.focus();
// Remove focus from any focused element
if (document.activeElement) {
document.activeElement.blur();
}
It is very well supported as well.
Active Element is pretty well supported. See: #5318915 –
Creolized
Benry — thanks for the link. I still think it needs to be feature tested though, the cost of a couple of property accesses is very low compared to a possible script error. Unfortunately my dev environment has just been upgraded to drop a buch of older browsers (not my choice) so I can't test in old stuff much any more. :-( –
Trolly
IE WARNING - see #3586639 –
Depressomotor
IE WARNING (like Jossef Harush): Stop using old IE and don't try to fix errors in the software, the problem is NOT yours. Advise your clients to upgrade. –
Megasporangium
@Erwinus—it's not necessarily the clients, it's the people who visit their web sites. IE 8 is still around 20% of web traffic for some sites. –
Trolly
@RobG: Put message on top of the page and offer some upgrade options via: browsehappy.com –
Megasporangium
@Erwinus—so find me a business that happily turns away 20% of visitors. Properly applied progressive enhancement will allow older browsers to use sites, perhaps not with all the bells and whistles but they should be functional. Of course if your site isn't a business site that makes money then your support requirements might be different. –
Trolly
"Do you really thing [sic] that somebody that is using an outdated browser is interested in buying stuff from you?" Yes, actually. Who told you that only people with the latest browsers buy stuff? And supporting customers is about more than just web sales. –
Trolly
It seems that the following code works...
document.activeElement.blur();
If no element is active, it will return the body element. If activeElement isn't supported, it will throw an error. –
Trolly
Typescript-friendly answer:
(document.activeElement as HTMLElement).blur();
Reference: https://github.com/Microsoft/TypeScript/issues/5901#issuecomment-396497729
© 2022 - 2024 — McMap. All rights reserved.
window.focus();
. Scrolling with arrow keys is enabled by focusing the window object... – Beaufort