Let's understand this with a simple program.
Do you know that we can add or remove a class to an element by JAVASCRIPT.
add
: this will add that class to that elementremove
: this will remove the given class from that elementtoggle
: this will add if the class is not present and remove the class if already been added.
const hello=document.getElementById("idname") //now hello get access to element which has id value equal to "idname"
hello.classList.add('classname') //classname class added to hello
hello.classList.remove('classname') //classname class removed to hello
hello.classList.toggle('classname') //classname class added/removed to hello
Copy the below code in your code editor to understand it properly
HTML CODE:
<div class="outer" id="outer">
<button class="change-btn" id="change-btn">Change Color</button>
</div>
CSS CODE:
.outer{
width: 200px;
height: 200px;
background-color: black;
}
.changeOuter{
background-color:lightgray;
}
JAVASCRIPT CODE:
const btn=document.getElementById("change-btn"),
outer=document.getElementById('outer')
btn.addEventListener('click',()=>{
outer.classList.toggle('changeOuter')
})
As were have used toggle here, when you first time clicks on that button it will add the changeOuter
class to the outer variable and when you click it the next time it will remove that class.
And every time you click, the background color of the outer div
is changing.
This is a basic example to let you know, how you can change the color using JAVASCRIPT.
Thank you for reading this article.