Show Element When Mouse Enters It, With JavaScript

Say you have an invisible element (like an action bar/menu) that you want to show when the user’s mouse enters that area. We can do that by setting up a JavaScript mouseenter event.

Gif showing a big red box when the user’s mouse enters it.

How to do it:

HTML markup

Add the following HTML code in your favorite editor (for online I recommend CodePen.

<div class="invisible-box">Yay you can see me!</div>
A div element with a invisible-box class

CSS styling

Add the following CSS to your stylesheet:

.invisible-box {
  opacity: 0;
  transition: all 500ms;
  padding: 32px;
  margin-top: 32px;
  margin-bottom: 32px;
  background-color: #cf4b32;
  color: #fff;
  text-align: center;
}

.opacity-1 {
  opacity: 1;
}

Notice that the .invisible-box class has opacity: 0; which means that it’s hidden by default. Right below we have a utility class .opacity-1 which we’ll use to show the element again with JavaScript.

JavaScript mouseenter event

Add the following code to your JS script:

let invisibleBox = document.querySelector(".invisible-box")

function addFullOpacity() {
  invisibleBox.classList.add("opacity-1")
}

invisibleBox.addEventListener("mouseenter", addFullOpacity)

How the JavaScript code works

  • First we use querySelector() to find and grab the .invisible-box. Then we assign it to a variable with a fitting name: invisibleBox.
  • Then we set up a function declaration and give it a name of addFullOpacity(). Inside its body {..} we add a statement.
  • The statement attaches the classList property’s add() method to our invisible box — and adds the opacity-1 class to our invisible box element.
  • Lastly, we set up addEventListener() and give it two arguments. The first argument listens for mouseenter event. The second argument is to call the addFullOpacity() function we created above (as soon as it registers a mouseenter event).

mouseenter vs mouseover?

You’ve probably noticed that there’s also an event type called mouseover — how does it differ from mouseenter?

The main difference is that:

  • The mouseover event triggers everytime the user’s mouse moves over the parent element or either of its child elements. It keeps triggering if you keep moving back and fourth elements — which can be expensive, performance-wise.
  • The mouseenter event triggers only when the mouse enters the target parent element — it doesn’t care about its children. :-(

You would want use mouseover if you have a web component that contains various features that you want to behave differently when users interact with them. Otherwise stick to mouseenter as it’s better for performance.

Resources


Has this been helpful to you?

You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊

Kofi

Share & Discuss on