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>
jsFiddle: link
In the example I created a function with 3 parameters, after 3 seconds there is a class transition with a CSS transition. I also used a native method, part of the native API classList . Assim podes adicionar e remover classes a um dados elemento. Podes ainda usar o
.toggle ('a_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 do not 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 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 .addEventListener
to know when a click
occurs and then toggle
to change the class. The this.innerHTML = aberto ? 'abrir' : 'fechar';
part is to change the button text (which is this
within that callback ). I also use .contains
to know if the element has a given class ...
jsFiddle: link
I hope I have given you something to use in your problem!