Erik Živković
Erik Živković

Reputation: 5415

How do you focus the body element if another element is already focused?

How do you place focus on the body / document.body element programatically, if another element is already focused?

Calling document.body.focus() does not seem to work, probably because body isn't focusable.

MDN Says

The HTMLElement.focus() method sets focus on the specified element, if it can be focused.

Upvotes: 2

Views: 2133

Answers (1)

Erik Živković
Erik Živković

Reputation: 5415

Chrome and Firefox both focus the document.body element if you first call .blur() on the currently focused element, and then call window.focus() immediately after.

Full solution (TypeScript):

    private focusBody = () => {
        if (document.activeElement instanceof HTMLElement) {
            document.activeElement.blur();
        }
        window.focus();
    };

Upvotes: 5

Related Questions