Firstly, Toggle does not serve to activate a class. What it does is to add a class if it is not already added. And if it’s already added he removes it.
To remove you use .remove('nomeDaClasse')
, and stop adding .add('nomeDaClasse')
.
I added an example below, for you to see in practice how it works:
function trocaClasse() {
var texto = document.getElementById("texto");
texto.classList.toggle('ativo');
}
function addClasse() {
var texto = document.getElementById("texto");
texto.classList.add('ativo');
}
function removeClasse() {
var texto = document.getElementById("texto");
texto.classList.remove('ativo');
}
.ativo {
color: red;
}
<button onClick="trocaClasse()">Testar - Toggle</button>
<button onClick="addClasse()">Testar - ADD</button>
<button onClick="removeClasse()">Testar - Remove</button>
<br>
<span id="texto" onClick="trocaClasse()">Clique no texto para trocar a cor</span>