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 will use event listeners to change image color. The event listener is used to change random color for the background color of the given image.
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.
HTML
<!DOCTYPE html> < html > < head > < title >random image color change</ title > </ head > < body > < img src = < div id = "divID" ></ div > </ body > </ html > |
CSS Code: We use CSS mix-blend-mode property to blend element content with parent content and background.
CSS
* { margin : 0 ; padding : 0 ; } #divID { position : absolute ; top : 0 ; width : 100% ; height : 100 vh; mix-blend-mode: hue; } body { overflow : hidden ; } img { height : 100 vh; width : 100% ; } |
JavaScript Code:
- First we use Math Floor() to select colors randomly.
- After that, we will add a click event listener to change the color.
Javascript
const divElem = document.getElementById( "divID" ); function randomcolor() { return Math.floor(Math.random() * 255); } divElem.addEventListener( 'click' , () => { divElem.style.backgroundColor = "rgba('+randomcolor()+','+randomcolor()+','+randomcolor()+'\)" }) |
Complete Code:
HTML
<!DOCTYPE html> < html > < head > < title >Random image color</ title > < style > * { margin: 0; padding: 0; } #divID { position: absolute; top: 0; width: 100%; height: 100vh; mix-blend-mode: hue; } body { overflow: hidden; } img { height: 100vh; width: 100%; } </ style > </ head > < body > < img src = < div id = "divID" ></ div > < script > const divElem = document.getElementById("divID"); function randomcolor() { return Math.floor(Math.random() * 255); } divElem.addEventListener('click', () => { divElem.style.backgroundColor = 'rgba(' + randomcolor() + ',' + randomcolor() + ',' + randomcolor() + '\)' }) </ script > </ body > </ html > |
Output: Click on the image to change color randomly.