Javascript beginner here. I essentially want to make a simple switch. If an element is black, change it to white. If it is white, change it to black.
function changeClass() {
if (document.getElementById('myButton').style.backgroundColor == "white") {
document.getElementById('myButton').style.backgroundColor = "black";
} else {
document.getElementById('myButton').style.backgroundColor = "white";
}
}
<button class="normal" id="myButton" onclick='changeClass()' >Change Colour</button>
This code is quite messy though. Is there a better way to do this?
Answer: Use the JavaScript style property You can easily change the background color of a webpage i.e. the <body> element or any other element dynamically by using its style property in JavaScript.
Use the String fontcolor() Method We can apply the fontcolor() method on any text string, and it returns the <font> HTML element with the color attribute.
The background-color CSS property sets the background color of an element.
Toggle a class:
function changeClass(){
document.getElementById('myButton').classList.toggle("the-class");
}
where your CSS is:
.the-class {
background-color: black;
}
...assuming the element's normal background color is white.
More about classList
here. Support is good, but you may need a polyfill in older environments.
Example:
function changeClass() {
document.getElementById('myButton').classList.toggle("the-class");
}
.the-class {
background-color: black;
}
<button class="normal" id="myButton" onclick='changeClass()'>Change Colour</button>
You can use classList.toggle()
document.querySelector('#myButton').addEventListener('click',e => {
e.target.classList.toggle('black')
})
.black{
background:black
}
<button class="normal" id="myButton">Change Colour</button>
Use something like classList.toggle()
function switchColor(){
document.getElementById("resultDiv").classList.toggle("toggle")
}
.element {
height: 100px;
width: 100px;
background-color: red;
}
.element.toggle{
background-color: blue !important;
}
<button onclick="switchColor()">Click me</button>
<div id="resultDiv" class="element toggle"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With