How to change background color according to the mouse location using JavaScript ?

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> <htmllang="en">  <head>     <metacharset="UTF-8"/>     <metaname="viewport"content=         "width=device-width,          initial-scale=1.0" />      <title>         How to change background          color according to mouse          location using JavaScript?     </title> </head>  <body>     <divclass="zambiatek"></div> </body>  </html>  | 
CSS Code: In CSS, we have just set the background color as cover.
| <style>     .zambiatek {         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>     vardiv =          document.querySelector(".zambiatek");      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> <htmllang="en">  <head>     <metacharset="UTF-8"/>     <metaname="viewport"content="width=device-width,                  initial-scale=1.0" />     <title>         How to change background color         according to mouse location         using JavaScript ?     </title>      <style>         .zambiatek {             width: 100%;             height: 600px;             background-size: cover;         }     </style> </head>  <body>     <divclass="zambiatek"></div>      <script>         var div =             document.querySelector(".zambiatek");          div.addEventListener(             "mousemove", function (e) {                 x = e.offsetX;                 y = e.offsetY;                 div.style.backgroundColor                     = `rgb(${x}, ${y}, ${x - y})`;             });     </script> </body>  </html>  | 
Output:
 
				 
					



