Question:
I have a javascript function that applies a certain style to some classes, and I would like to know how I can remove this style by clicking on the same button.
var botao = document.getElementById("troca");
var cores = document.getElementsByClassName("cores");
function aplicaCores() {
for (var i = 0; i < cores.length; i++) {
cores[i].style.background = "red";
}
}
botao.onclick = aplicaCores;
Answer:
Create CSS classes that apply these colors instead of applying them directly to HTML.
And then you can create a function that adds and removes a class (this is called toggle):
var botao = document.getElementById("troca");
var cores = document.getElementsByClassName("cores");
function aplicaCorVermelha() {
for (var i = 0; i < cores.length; i++) {
cores[i].classList.toggle('red');
}
}
botao.onclick = aplicaCorVermelha;
CSS:
.red {
background-color: red;
}
Or a function that adds a given class, overriding the old one:
var verde = document.getElementById("green");
var vermelho = document.getElementById("red");
var cores = document.getElementsByClassName("cores");
function aplicaCor() {
var cor = this.id
for (var i = 0; i < cores.length; i++) {
cores[i].className = cor;
}
}
verde.onclick = aplicaCor;
vermelho.onclick = aplicaCor;
CSS:
.red {
background-color: red;
}
.green {
background-color: green;
}