DEV Community

Saroj Pradhan
Saroj Pradhan

Posted on • Edited on

2 1

Change color in each click using JavaScript

While developing webpages, if you have ever wondered how a user will be able to switch the color of an HTML element, then this task can be easily achievable with a little help of JavaScript.

In the below example, we will be changing the background color of the div element with a class named “container” whenever the button with id “click” is clicked. We will implement a JavaScript session in order to keep track of the user-selected color.

<div class="container" id="container">
    <button id="click" onclick="clickHere()">Click to Change color</button>
</div>
Enter fullscreen mode Exit fullscreen mode
body{
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
}
.color{
    color:blue;
}
.container{
    height: 300px;
    width:400px;
    background-color: purple;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 10px;
}
#click{
    padding: 1rem 1rem;
    border:none;
    border-radius: 10px;
    cursor:pointer;
    font-size:16px;
}
Enter fullscreen mode Exit fullscreen mode
//array of color values
var color = ["red", "blue", "green", "orange", "yello", "cyan", "gray", "skyblue", "lightblue", "lightgreen"]

function clickHere(){
    // store the count of click in session 
    var count = sessionStorage.getItem("count")
    if(count !== null){
        // if the session/count exists then increment it with 1.
        sessionStorage.setItem("count",parseInt(count)+1)
    }else{
        // if the session/count is null i.e first click then start with 0
        // because our first array index is 0 i.e color[0] = "red"
        sessionStorage.setItem("count",0)
    }

    var newCount = sessionStorage.getItem("count")

  //get the session value to map the color index in color array
 document.getElementById("container").style.backgroundColor = color[parseInt(newCount)]

  // if the click count matches array length then reset the session value.
  // -1  in color.length because color.length gives 10 but final array index is 9.
    if (newCount == color.length-1){
        sessionStorage.removeItem("count")
    }
}
Enter fullscreen mode Exit fullscreen mode

Open in Codepen

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay