How to create a mouseover effect with JavaScript addEventListener?

Sometimes, we want to create a mouseover effect with JavaScript addEventListener.

In this article, we’ll look at how to create a mouseover effect with JavaScript addEventListener.

How to create a mouseover effect with JavaScript addEventListener?

To create a mouseover effect with JavaScript addEventListener, we can pass in a callback to set the styles to create the mouseover effect.

For instance, we write:

<button>
  click me
</button>

to add a button.

Then we write:

const button = document.querySelector("button");

button.addEventListener("mouseover", () => {
  button.setAttribute("style", "background-color: blue;")
});
button.addEventListener("mouseout", () => {
  button.setAttribute("style", "background-color: red;")
});

to select the button with querySelector.

Then we call button.addEventListener to add the mouseover and mouseout event listeners.

The callback sets the background of the button to blue when we hover over the button and sets it to red when we move our mouse away from it.

Conclusion

To create a mouseover effect with JavaScript addEventListener, we can pass in a callback to set the styles to create the mouseover effect.