Categories
JavaScript Answers

How to run JavaScript when an element loses focus?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *