To give you something to learn take a look at this example:
function trocaClasse(elemento, antiga, nova) {
elemento.classList.remove(antiga);
elemento.classList.add(nova);
}
setTimeout(function() {
var div = document.querySelector('div');
trocaClasse(div, 'azul', 'verde');
}, 2000);
div {
padding: 50px;
transition: background-color 1s;
}
.azul {
background-color: #00b;
}
.verde {
background-color: #0b0;
}
<div class="azul"></div>
In the example I created a function with 3 parameters, after 3 seconds there is a class change with a CSS transition. I also used a native method, part of the classList native API. Assim podes adicionar e remover classes a um dados elemento. Podes ainda usar o
.toggle('uma_class');` which is like a switch, strip and put the class every time you run.
using an event
You can do similar things with events calling this function. Often you don’t need 2 classes, but only one. The absence of the class already does what is intended, one of the states.
Another example, similar to the one above but with events:
var menu = document.querySelector('div.menu');
var botao = document.querySelector('button#interruptor');
botao.addEventListener('click', function() {
var aberto = menu.classList.contains('abrir');
menu.classList.toggle('abrir');
this.innerHTML = aberto ? 'abrir' : 'fechar';
});
.menu {
padding: 50px;
margin-top: -100px;
transition: margin-top 1s;
background-color: #ccf;
margin-bottom: 10px;
}
.abrir {
margin-top: 0px;
}
<div class="menu"></div>
<button id="interruptor" type="button">abrir</button>
In this example I use the .addEventListener
to know when a click
occurs and then the toggle
to change the class. The this.innerHTML = aberto ? 'abrir' : 'fechar';
is to swap the button text (which is the this
within that callback). I also use the .contains
to know if the element has a given class...
I hope I gave you something to use on your problem!
You can better explain the functionality you are looking for?
– Sergio
I have a menu in html with a menu-disable class that is when it is closed, I need to change this class to menu-active that will be when it is open. So I need a function to make this class change with onclick.
– João Victor
uses the functions of jQuery addClass(') and removeClass(') or toggleClass('')
– Marcelo Bonus