pjk_ok
pjk_ok

Reputation: 947

How to toggle an event on a Class node list

I'm trying to toggle a javascript event on a class node list. I've done a simplified version of the problem below.

The initial event is being executed, but the second event to toggle the button back to red doesn't seem to be working? JS and link to Codepen below.

Codepen is here: https://codepen.io/emilychews/pen/EXmzbd?editors=1010

JS

  var clicked = false;

  var $mainMenuButton = document.getElementsByClassName('desktopmenubutton');

if (clicked === false) {
     for (h = 0; h < $mainMenuButton.length; h+=1) {
      $mainMenuButton[h].addEventListener('click', function (e){
        e.currentTarget.style.background = "black";
        clicked = true;  // change clicked state to true
      });    
   }
} else {
    for (i = 0; i < $mainMenuButton.length; i+=1) {
      $mainMenuButton[i].addEventListener('click', function (e){
        e.currentTarget.style.background = "red";
        clicked = false;
      });
    } 
}

Upvotes: 0

Views: 313

Answers (1)

David Marcus
David Marcus

Reputation: 474

You only need one event listener to get this to work.

var $mainMenuButton = document.getElementsByClassName('desktopmenubutton');


for (h = 0; h < $mainMenuButton.length; h += 1) {
  $mainMenuButton[h].addEventListener('click', function(e) {
    if (e.currentTarget.style.backgroundColor == "red" || e.currentTarget.style.backgroundColor == "") {
      e.currentTarget.style.backgroundColor = "black";
    } else {
      e.currentTarget.style.backgroundColor = "red";
    }
  });
}
* {font-family: arial;}

.desktopmenubutton {
  width: 150px;
  height: 100px;
  background-color: red;
  position: absolute;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white
}

.button2 {
  left: 300px;
}
<div class="desktopmenubutton button1">Button 1</div>
<div class="desktopmenubutton button2">Button 2</div>

Upvotes: 1

Related Questions