How to hide a div when it loses focus with JavaScript?

Sometimes, we want to hide a div when it loses focus with JavaScript.

In this article, we’ll look at how to hide a div when it loses focus with JavaScript.

How to hide a div when it loses focus with JavaScript?

To hide a div when it loses focus with JavaScript, we can listen to the mouseup event on the document.

And if we lift our mouse button anywhere outside the div, then we hide the div.

For instance, we write:

<div>
  hello world
</div>

to add a div.

Then we write:

const div = document.querySelector('div')
document.onmouseup = (e) => {
  if (e.target !== div) {
    div.style.display = 'none'
  }
}

to select a div.

Then we set document.onmouseup to a function that checks if the element being clicked isn’t a div with e.target !== div.

e.target is the element where the event is being triggered.

If it’s true, then we set the display CSS property of the div to 'none' to hide it.

Conclusion

To hide a div when it loses focus with JavaScript, we can listen to the mouseup event on the document.

And if we lift our mouse button anywhere outside the div, then we hide the div.