Explain Codes LogoExplain Codes Logo

Run JavaScript when an element loses focus

javascript
event-delegation
debouncing
focusout
Alex KataevbyAlex Kataev·Dec 15, 2024
TLDR

To execute JavaScript when an element loses focus, use the blur event listener.

document.querySelector('#elementID').addEventListener('blur', () => { // This is where the magic happens (Or your code, same thing 😉) alert('Element lost focus'); });

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.

<input type="text" onblur="console.log('Ninja vanish!');" />

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.

function validateInput(inputElement) { if (inputElement.value.length < 3) { console.error('Only three? Is it your lucky number?'); } } document.querySelector('#username').addEventListener('blur', function() { validateInput(this); });

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.

document.querySelector('#formIO').addEventListener('focusout', (event) => { console.log('Mission completed: Lost Focus!'); });

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.

let dropdown = document.querySelector('#dropdown'); dropdown.addEventListener('blur', (event) => { if (!dropdown.contains(event.relatedTarget)) { console.log('Busted! This ghost is toast.'); } }, true);

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.

let timer; function debounceBlur(fn, delay) { return function() { clearTimeout(timer); timer = setTimeout(() => fn.apply(this, arguments), delay); }; } document.querySelector('#inputField').addEventListener('blur', debounceBlur(() => { console.log('Too fast, too furious? Chill, I can handle it.'); }, 300));

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.

document.querySelector('#container').addEventListener('focusout', (event) => { console.log('I see the light at the end of the tunnel!'); });