2
I am trying to make on a page, that buttons that are clicked change their style and also start to display a div when they are clicked. Only that they should be mutually exclusive, that is, when I click on one, only the div attached to the button should be displayed and only the button clicked should have its style changed. The code I have used is as follows::
//Adiciona eventos a cada botão
//Classe CSS 'side-button' para estado padrão e 'clicked-button' quando clicado
function buttonEventDef(){
var current;
for(var i=0; i<btns.length; i++){
current = i;
btns[i].addEventListener('click', function(){
this.classList.remove('side-button');
this.classList.add('clicked-button');
show[current].style.display = 'initial';
for(var j=0; j<btns.length; j++){
if(j!=current){
btns[j].classList.remove('clicked-button');
btns[j].classList.add('side-button');
show[j].style.display = 'none';
}
}
});
}
}
But when I press a button he remembers his style, even after I press another button. The Divs feel the same way about visibility.
Actually, there’s a better way to do that?
That worked, thank you very much! I can only know why to put the function inside the first is inside in parentheses, and also why to open and close after these?
– Hian Neiva
@Hianneiva am glad to have helped. Take a look here at Iifes: http://answall.com/a/23788/129
– Sergio
Now I understand. It is important to know about the Iifes since sometimes JS can confuse as to the scope of variables and functions. Again, thank you very much!
– Hian Neiva