How to run JavaScript when an element loses focus?

Sometimes, we want to run JavaScript when an element loses focus.

In this article, we’ll look at how to run JavaScript when an element loses focus.

How to run JavaScript when an element loses focus?

To run JavaScript when an element loses focus, we can listen for the blur event.

For instance, we write

<input type="text" name="name" value="value" />

to add an input.

Then we write

const input = document.querySelector("input");
input.onblur = () => {
  alert(1);
};

to select the input with querySelector.

And then we set input.onblur to a function that calls alert to show an alert box when we move our focus away from the input.

Conclusion

To run JavaScript when an element loses focus, we can listen for the blur event.