Categories
JavaScript Answers

How to Run JavaScript Code When an Element Loses Focus?

Spread the love

Listen to the blur Event

We can listen to the blur event to run code when an element loses focus.

For instance, if we have the following input element:

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

Then we can watch when the blur event is triggered on the input by writing:

const input = document.querySelector('input')  
input.addEventListener('blur', () => {  
  console.log('focus lost')  
})

We get the input element with document.querySelector .

Then we call addEventListener on it with 'blur' as the first argument.

The 2nd argument is a callback that runs when the blur event is triggered.

When we move our cursor away from the input element, we’ll see the 'focus lost' string logged.

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 *