I\'d like to implement some javascript that uses an if statement to change some css styles. Not sure how to do it, any help would be great!
If you want to change a single style of an element using JavaScript, use
document.getElementById(id).style.property = new style
eg :
document.getElementById("myDiv").style.color= "red";
To add a new CSS class to an element, use
document.getElementById(id).classList.add("mystyle");
To remove
document.getElementById(id).classList.remove("mystyle");
Demo :
function changeSingleStyle() {
var color = document.getElementById("myDiv").style.color;
if (color === "red")
document.getElementById("myDiv").style.color = "yellow";
else
document.getElementById("myDiv").style.color = "red";
}
function addClass() {
document.getElementById("myDiv").classList.add("mystyle");
}
function removeClass() {
document.getElementById("myDiv").classList.remove("mystyle");
}
.mystyle {
color : red;
background: green;
font-size: 50px;
}
<div id="myDiv"> This is a div </div>
<button onclick="changeSingleStyle()">changeSingleStyle</button>
<button onclick="addClass()">addClass</button>
<button onclick="removeClass()">removeClass</button>
First of all, to change CSS using JavaScript, the syntax looks like the following:
document.getElementById(id).style.property = new style
For example, if you want to change the display property of an element with id = "container" to block, it would be:
document.getElementById("container").style.display = "block";
Given this, you could easily add an IF statement depending on what condition you want. For example:
if(condition)
{
document.getElementById("container").style.display = "block";
}