How to Randomly Change Image Color using HTML CSS and JavaScript ?


In this tutorial, we will look at two approaches to change the image color randomly using HTML, CSS and JavaScript.

Approach 1: Using Math.random() Function

We will begin by writing the HTML code and use the <img> tag to select the target image. Then we will apply some basic some basic styles using CSS properties. In order to select colors randomly, we have to use the JavaScript Math.random() function. Math.random() generates a number at random between 0 (inclusive) and 1 (exclusive). To change the color of the image, we will use event listeners. The event listener is used to change the background color of the given image at random.

Example

<!DOCTYPE html>
<html>
<head>
    <title>How to randomly change image color using HTML CSS and JavaScript ?</title>
</head>
<style>
    body {
        overflow: hidden;
    }
    #container {
        top:0;
        width: 350px;
        height: 150px;
        position: absolute;
        mix-blend-mode: hue;
    }
    img {
        height: 150px;
        width: 350px;
    }
    p {
        font-size: 20px;
        font-weight: bold;
        margin-left: 15px;
    }
</style>
  
<body>
    <img src="https://www.tutorialspoint.com/images/logo.png">
    <div id="container"></div>
    <p>Click the image to change its color</p>
    <script>
        const divElement = document.getElementById("container");
        function selectcolor() {
            return Math.floor(Math.random() * 255);
        }
        divElement.addEventListener('click', () => {
            divElement.style.backgroundColor = 'rgba(' 
                + selectcolor() + ',' + selectcolor() 
                + ',' + selectcolor() + '\)'
        })
    </script>
</body>
</html>

Approach 2: Using Math Functions with Hexadecimal Color Code

In this approach we will use the onclick event to trigger a button which will eventually trigger the color change of the image. We will establish this using Math.random() and Math.floor() functions along with hexColorCode.

We will follow a series of steps to implement this approach.

  • First, we will write the HTML code with div comtainer and enclose our target image within it. After this, we will include a clickable button which will be responsible for the color change of the image.

  • Next, we will design the entire layout including our div container, image and button using CSS styling properties. Using the CSS animation property, we will animate the p tag. In our CSS, we'll give the p selector the animation property and a name value of 'hexcolors.' It will last 5 seconds and will be infinitely alternate. It changes the colour of the text.

  • We then proceed to create @keyframes with the name hexcolors. Keyframes describe how an animated element appears at a specific point in the animation sequence. The text animation will start at 0%. It will have violet color at 0%, indigo color at 20%, blue color at 40%, green color at 60%, yellow color at 80% and orangered color at a 100%.

  • Lastly, we create a function in JavaScript with an array consisting of hex numbers. The hex code will then be generated using the built-in Math functions. Using document.getElementById, we can get the id of the span tag. This will change the screen's display of the hexadecimal colour code. Next, we get the image tag as well by using document.getElementByTagName; this will change the background colour of the image when you click the button.

Example

<!DOCTYPE html>
<html>
    <head>
        <title>How to randomly change image color using HTML CSS and JavaScript ?</title>
        <style>
            body {
            background-color: paleturquoise;
            }
            .container {
            width: 75%;
            height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            text-align: center;
            margin: auto;
            }
            h3 {
            font-size: 18px;
            margin: 10px 20px 20px 10px;
            color: white;
            }
            .btn1 {
            padding: 2% 2%;
            border: none;
            border-radius: 4px;
            color: teal;
            font-size: 15px;
            cursor: pointer;
            }
            img{
                width: 400px;
                height: 200px;
                border: 2px solid white;
            }
            p{
                animation: hexcolors 5s infinite alternate;
                font-size: 20px;
                font-weight: bold;
                color: navy;
            }
            @keyframes hexcolors {
                0% {
                    color: violet;
                }
                20% {
                    color: indigo;
                }
                40% {
                    color: blue;
                }
                60% {
                    color: green;
                }
                80% {
                    color: yellow;
                }
                100% {
                    color: orangered;
                }
            }
            @media screen and (min-width: 992px) {
            /* For Large Laptops */
            .container {
                width: 100vw;
                margin: auto;
            }
            h2 {
                font-size: 30px;
            }
            .btn1 {
                padding: 2% 2%;
                margin: auto;
                font-size: 20px;
                font-weight: bold;
            }
            }
        </style>
    </head>
    <body>
        <div class="container">
            <div>
              <p>Click the button to change the color of the image.</p>
              <img src="https://www.tutorialspoint.com/images/logo.png">
              <h3>The background color is : # <span id="colorCode">0f5257</span></h3>
              <button onclick="changeColor()" class="btn1">
                Generate Color
              </button>
            </div>
          </div>
          <script>
              function changeColor() {
                let hexNumbers = [
                    "0",
                    "1",
                    "2",
                    "3",
                    "4",
                    "5",
                    "6",
                    "7",
                    "8",
                    "9",
                    "A",
                    "B",
                    "C",
                    "D",
                    "F",
                ];
                let hexColorCode = "";
                for (var i = 0; i < 6; i++) {
                    let randomIndex = Math.floor(Math.random() * hexNumbers.length);
                    hexColorCode += hexNumbers[randomIndex];
                }
                document.getElementById("colorCode").innerHTML = hexColorCode;
                document.getElementsByTagName("img")[0].style.background =
                    "#" + hexColorCode;
                }
          </script>
    </body>
</html>

Updated on: 12-Sep-2023

264 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements