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 formouseover
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.
For color values you can either use real names (like "red"), hex or rgba values.