Run JavaScript when an element loses focus
To execute JavaScript when an element loses focus, use the blur
event listener.
In this case, replace #elementID
with the ID of your specific target and replace the alert
function with your particular JavaScript code.
Inline implementation using onblur
A straight up way to perform this action can be embedding the onblur
attribute directly within the HTML code of the input element. This works like a charm for simple uses.
This will log 'Ninja vanish!' to the console when the input field loses focus. Feel the power of instant feedback!
Embracing the power of onblur and focusout
Real-time form validation with onblur
With onblur
, interactive user forms can level up. It enables real-time validation of user inputs as soon as the user switches fields.
Focusout, the alternative hero
While onblur
is a fan favorite, onfocusout
enters the game as an alternative with a killer feature: it bubbles up. This makes it effective for event delegation.
Pro tips and tricks
Focus Jedi: Managing complex UIs such as modals/dropdowns
blur
events in modals or dropdowns sometimes feel like crossing the streams in Ghostbusters, things explode! Parent blur also triggers when child elements lose focus, causing unexpected behavior.
Preventing blur in quick interactions
Rapid-fire users might unintentionally trigger blur, like users who CYCLE THROUGH INPUTS faster than The Flash. Debouncing helps us not to make the Justice League jealous.
Choose your fighter: blur or focusout
As a developer, choose your heroes wisely. If you're tracking focus within a CONTAINER, consider the bubble-capable focusout
.
Was this article helpful?