The background color can be changed according to the cursor position using the DOM (Document Object Model). In this article, we use the position of the cursor to set the value of the background.
Approach: The approach is to use DOM manipulation to change the background according to the cursor position at a particular time.
HTML Code: In this section, we have a simple boiler-plate code of HTML with a div tag in it.
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" /> < meta name = "viewport" content= " width = device -width, initial-scale = 1 .0" /> < title > How to change background color according to mouse location using JavaScript? </ title > </ head > < body > < div class = "neveropen" ></ div > </ body > </ html > |
CSS Code: In CSS, we have just set the background color as cover.
<style> .neveropen { width : 100% ; height : 600px ; background- size : cover; } </style> |
Note: You can set a default background.
Javascript Code: In JS, first select the div tag using querySelector function and we have offset property to get the position of the cursor on the 2-D plane i.e. the X and Y-axis. Now we set the value of background using the co-ordinates.
<script> var div = document.querySelector( ".neveropen" ); div.addEventListener( "mousemove" , function (e) { x = e.offsetX; y = e.offsetY; div.style.backgroundColor = `rgb(${x}, ${y}, ${x - y})`; }); </script> |
Complete Code: It is the combination of the above three sections of code.
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" /> < meta name = "viewport" content=" width = device -width, initial-scale = 1 .0" /> < title > How to change background color according to mouse location using JavaScript ? </ title > < style > .neveropen { width: 100%; height: 600px; background-size: cover; } </ style > </ head > < body > < div class = "neveropen" ></ div > < script > var div = document.querySelector(".neveropen"); div.addEventListener( "mousemove", function (e) { x = e.offsetX; y = e.offsetY; div.style.backgroundColor = `rgb(${x}, ${y}, ${x - y})`; }); </ script > </ body > </ html > |
Output: