Change color in each click using JavaScript
Published On: May 11th, 2023
In order to change the color/background-color (applicable to other CSS styling as well) of an HTML element, it can be easily achieved using a session in vanilla javascript.
In the below example, I will be changing the background color of the div element with a class named “container” whenever the button with id “click” is clicked.
HTML
<div class="container" id="container"> <button id="click" onclick="clickHere()">Click to Change color</button> </div>
CSS
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; }
JavaScript
//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") } }