[Solved] Mouse Gradient Task in HTML with DOM and JavaScript

  

3
Topic starter

Write a JS program that detects and displays how far along a gradient the user has moved their mouse on a webpage. Use the provided HTML and stylesheet (CSS) to test locally. The resulting value should be rounded down and displayed as a percentage inside the <div> with ID "result".

Input/Output:
There will be no input/output, your program should instead modify the DOM of the given HTML document.

Sample HTML:

<html>
<head>
  <title>Mouse in Gradient</title>
  <link rel="stylesheet" href="gradient.css" />
  <script src="gradient.js"></script>
</head>
<body onload="attachGradientEvents()">
  <div id="gradient-box">
    <div id="gradient">Click me!</div>
  </div>
  <div id="result"></div>
</body>
</html>

CSS:

#gradient-box {
  width: 300px;
  border: 2px solid lightgrey;
}
#gradient-box:hover {
  border: 2px solid black;
}
#gradient {
  height: 30px;
  color: white;
  text-shadow: 1px 1px 10px black;
  text-align: center;
  line-height: 30px;
  background: linear-gradient(to right, black, white);
  cursor: crosshair;
}

Examples:

mouse gradient javascript task

1 Answer
2

My solution:

HTML file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Mouse in Gradient</title>
    <link rel="stylesheet" href="gradient.css"/>
    <script src="gradient.js"></script>
</head>
<body onload="attachGradientEvents()">
<div id="gradient-box">
    <div id="gradient">Click me!</div>
</div>
<div id="result"></div>
</body>
</html>

CSS file (gradient.css):

#gradient-box {
    width: 300px;
    border: 2px solid lightgrey;
}
 
#gradient-box:hover {
    border: 2px solid black;
}
 
#gradient {
    height: 30px;
    color: white;
    text-shadow: 1px 1px 10px black;
    text-align: center;
    line-height: 30px;
    background: linear-gradient(
            to right, black, white);
    cursor: crosshair;
}

JavaScript file (gradient.js):

function attachGradientEvents() {
    let gradient = document.getElementById('gradient');
    gradient.addEventListener('mousemove', gradientMove);
    gradient.addEventListener('mouseout', gradientOut);
    function gradientMove(event) {
        let power = event.offsetX / (event.target.clientWidth - 1);
        power = Math.trunc(power * 100);
        document.getElementById('result').textContent = power + "%";
    }
    function gradientOut(event) {
        document.getElementById('result').textContent = "";
    }
};
Share: