In this article, we will create a webpage where we can change image color randomly by clicking on the image using HTML, CSS, and JavaScript. The image color will change randomly using the JavaScript Math random() function.
Approach:
- First of all select your image using HTML <img> tag.
- In JavaScript, use the Math random() function to select colors randomly.
- We use an event listener to apply a random hue-rotate() filter that changes the image color on click.
HTML Code:
- Create an HTML file.
- Create a body and select your image using the HTML <img> src.
- Inside the HTML body tag, create an HTML div and give an id to this.
<!DOCTYPE html>
<html>
<head>
<title>Random image color change</title>
</head>
<body>
<img
id="img"
src="https://media.geeksforgeeks.org/wp-content/uploads/20220803165300/geeksimage-200x145.png">
</body>
</html>
CSS Code: We use CSS mix-blend-mode property to blend element content with parent content and background.
* {
margin: 0;
padding: 0;
}
body {
overflow: hidden;
}
img {
height: 100vh;
width: 100%;
cursor: pointer;
transition: filter 0.3s ease;
}
JavaScript Code:
- Use Math Floor() with Math.random() to generate a random degree value.
- Add a click event listener to the image.
- Apply a random hue-rotate() CSS filter to change the image color.
const img = document.getElementById("img");
function randomDegree() {
return Math.floor(Math.random() * 360);
}
img.addEventListener("click", () => {
img.style.filter = `hue-rotate(${randomDegree()}deg)`;
});
Complete Code:
<!DOCTYPE html>
<html>
<head>
<title>Random image color change</title>
<style>
* {
margin: 0;
padding: 0;
}
body {
overflow: hidden;
}
img {
height: 100vh;
width: 100%;
cursor: pointer;
transition: filter 0.3s ease;
}
</style>
</head>
<body>
<img
id="img"
src="https://media.geeksforgeeks.org/wp-content/uploads/20220803165300/geeksimage-200x145.png">
<script>
const img = document.getElementById("img");
function randomDegree() {
return Math.floor(Math.random() * 360);
}
img.addEventListener("click", () => {
img.style.filter = `hue-rotate(${randomDegree()}deg)`;
});
</script>
</body>
</html>
Output: Click on the image to change color randomly.
