How to Change the Background Color on a Website (on mouseover) With JavaScript

Learn how to change the background color on a website when you move your mouse over it, with vanilla JavaScript.

HTML

Here’s some markup for a simple HTML page:

<!DOCTYPE html>
<html>
  <body>
    <h1>Move your move over this page</h1>
  </body>
</html>

JavaScript

To change the background color when a user moves their mouse over any part of the page, you need to:

  • Target the <body> element and store a reference to it in a variable.
  • An event listener on the window object that listens for mouseover events.
  • Apply the backgroundColor property with a color value.

Add the following code to your JavaScript file:

const bodyElement = document.querySelector("body")

window.addEventListener("mouseover", function() {
  bodyElement.style.backgroundColor = "red"
})

Now as soon as the user moves their mouse over any part of your website, the background color instantly turns red.

Check out the code demo.

For color values you can either use real names (like "red"), hex or rgba values.


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