DEV Community

Saroj Pradhan
Saroj Pradhan

Posted on • Updated on

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

Top comments (0)