Open In App

How to Change Background Color According to Mouse Location using JavaScript?

Last Updated : 12 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

To change the background color based on the mouse location in JavaScript, we can track the cursor’s position on the screen and adjust the background color as the mouse moves. This is done by capturing the X and Y coordinates of the mouse and applying those values to change the background color dynamically.

  • HTML: We start with a simple HTML structure, including a div that will act as the canvas for changing the background color based on the cursor’s position.
  • CSS: Basic CSS is applied to give the div full width and height, ensuring it covers the entire page.
  • JavaScript: We track the mouse’s movement using the mousemove event. By capturing the X and Y coordinates, we dynamically update the background color based on the cursor’s position.
HTML
<div class="geeks"></div>
CSS
.geeks {
	width: 100%;
    height: 600px;
    background-size: cover;
}
JavaScript
let div = document.querySelector(".geeks");

div.addEventListener("mousemove", function (e) {
	x = e.offsetX;
    y = e.offsetY;
    div.style.backgroundColor = `rgb(${x}, ${y}, ${x - y})`;
});

Output



Next Article

Similar Reads