.blur()
Example
menuItem.addEventListener('click', () => {
closeMenu();
menuItem.blur();
});menuItem.addEventListener('click', () => {
closeMenu();
menuTrigger.focus();
});Blurring drops focus to the body, so keyboard users lose their place; move focus to a meaningful element.
Common mistakes
- Calling
blur()after a click to hide the outline, which breaks keyboard navigation. - Expecting the
blurevent to bubble for delegation;focusoutdoes.
Key points
- Focus is moved to a meaningful element with
focus()instead of being dropped withblur(). - Focus rings are not hidden by calling
blur()on click;:focus-visiblestyling is used instead.
Interview questions
blur vs focusout?
Both fire when an element loses focus, but focusout bubbles and blur does not, so event delegation needs focusout.
Where does focus go after blur()?
To the document body: document.activeElement becomes document.body.
How do I hide the focus ring on mouse click?
Style :focus-visible instead of :focus. Browsers usually skip the ring for mouse clicks on buttons and keep it for keyboard users.