Javascript style buttons

Asked

Viewed 166 times

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?

1 answer

0


To keep this one i/current within the cycle for you need to create a new scope. That way you can save for example var thisIndex = i; and make sure that this value is kept in memory and is not rewritten in the next iteration of the cycle for.

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: http://jsfiddle.net/mxe1h0e2/

  • 1

    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?

  • @Hianneiva am glad to have helped. Take a look here at Iifes: http://answall.com/a/23788/129

  • 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!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.