JavaScript style buttons

2

I'm trying to do on a page, that buttons that are clicked change their style and also show a div when clicked. Only that they must be mutually exclusive, that is, when I click on one, only the div attached to the button should be displayed and only the clicked button should have its style changed. The code I have used is the following:

//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 it slows down your style even after I press another button. The divs have the same behavior as visibility.

Is there a better way to do this?

    
asked by anonymous 11.05.2015 / 23:26

1 answer

0

To save this i / current within the for cycle you must create a new scope. This way you can save var thisIndex = i; and make sure that this value stays in memory and is not rewritten in the next iteration of the for cycle.

Suggestion:

for (var i = 0; i < btns.length; i++) {
    (function () {
        var thisIndex = i;
        btns[i].addEventListener('click', function () {
            this.classList.remove('side-button');
            this.classList.add('clicked-button');
            show[thisIndex].style.display = 'initial';

            for (var j = 0; j < btns.length; j++) {
                if (j != thisIndex) {
                    btns[j].classList.remove('clicked-button');
                    btns[j].classList.add('side-button');
                    show[j].style.display = 'none';
                }
            }
        });
    })();
}

jsFiddle: link

    
11.05.2015 / 23:39