Skip to content
Related Articles

Related Articles

Improve Article

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

  • Last Updated : 08 Jun, 2020

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="geeks"></div>
</body>
  
</html>

CSS Code: In CSS, we have just set the background color as cover.




<style>
    .geeks {
        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(".geeks");
  
    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>
        .geeks {
            width: 100%;
            height: 600px;
            background-size: cover;
        }
    </style>
</head>
  
<body>
    <div class="geeks"></div>
  
    <script>
        var div =
            document.querySelector(".geeks");
  
        div.addEventListener(
            "mousemove", function (e) {
                x = e.offsetX;
                y = e.offsetY;
                div.style.backgroundColor
                    = `rgb(${x}, ${y}, ${x - y})`;
            });
    </script>
</body>
  
</html>

Output:

Attention reader! Don’t stop learning now. Get hold of all the important Comcompetitivepetitve Programming concepts with the Web Design for Beginners | HTML  course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :