Play Blur onblur
Mads Stoumann
Posted on December 18, 2021
Yesterday, a colleague asked me what we should do onfocusout
on a task, we're working on. I told him it's called onblur
in JavaScript (we were both right, more on this later!)
To this, another colleague said:
“Is this a reference to the band? Otherwise, it's a shitty name”.
(if you're not familiar with the band Blur or the onblur
-event, this probably isn't funny at all)
… maybe it is a shitty name, but what if we could play Blur onblur
?
First, we need to add an audio-file:
<audio src="woohoo.mp3" hidden id="woohoo"></audio>
We'll give it an id, woohoo
, so we can easily reach it from code.
Then, we'll add a fieldset, with some inputs:
<fieldset id="app">
<legend>Play Blur onblur</legend>
<label>♪ Woohoo<input type="text" /></label>
<label>♫ Woohoo<input type="text" /></label>
<label>♫ Woohoo<input type="text" /></label>
</fieldset>
And finally, a little snippet of JavaScript, where we iterate the elements
-collection of the fieldset, and add an onblur
-eventListener to each input:
[...app.elements].forEach(input => input.addEventListener('blur', function(e) {
woohoo.play()
}))
And that's it! Now focus on a field and leave it ;-)
Real use-cases
Okay, so admittedly this is just plain stupid, but maybe we could actually use this technique in conjunction with the Constraint validation API?
If a form-field is valid, it could play a tiny "ding!"-sound, and if it's invalid, a tiny "buzz"-sound.
focusout
Turns out my colleague was right: there is an event called focusout
(and it's counter-part: onfocusin
) – I'm just so old-school, that I've used focus
and blur
for ages!
Unlike blur
, onfocusout
actually bubbles up, meaning we can add a single event to the fieldset instead:
app.addEventListener('focusout', () => woohoo.play)
– but it's not funny at all to play Blur onfocusout
, is it? 😂
In conslusion: Thank you to my colleagues for giving me an excuse to code something stupid and learning about the onfocusout
-event!
Posted on December 18, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.