Search code examples
javascripthtmlfunctionbooleantoggle

How do I toggle a bool by calling a function via onClick?


I'm brand spanking new to javascript and I tried searching through StackOverflow but couldn't find an answer to my issue.

I made a function to modify some HTML elements (i.e. change color) based on a boolean value when a button is pressed. I try to call the function and pass in variables through the HTML onclick command in my button, but the boolean is not being toggled properly. The color of the element changes as if the bool were true, but never changes back. I suspect that it is not grabbing the correct boolean from my .js file, but instead making a new boolean from the bool parameter. I have two questions actually:

  1. Am I correct in my assumption of the problem?
  2. How can I make this work?

Here's my code snippet:

const myBtn = document.querySelector('.js-myBtn');
let myBool = false;

function buttonToggle(bool, button) {
  bool = !bool;
  if (bool) {
    button.style.color = 'green';
  } else {
    button.style.color = 'white';
  }
}
<button class="js-myBtn" onclick="buttonToggle(myBool, myBtn)">TOGGLE</button>

Normally I wouldn't use a generic function, but I have 15 different buttons and I would rather not write a specific function for each button. Any help would be greatly appreciated. I apologize if this is stupidly obvious or if I'm missing something, I've been in a bit of a time crunch.

Apart from the function call in the onclick command shown above, I've tried assigning an eventListener to each button in my .js code and running the function through there (wrapped in an anonymous function), but the same issue happens. I've tried linking my script file in the head (I know that's not a good idea, but I just wanted to see what would happen). I've also tried to put the boolean in an array and pass that in...silly, I know but I don't have anyone to ask at work (I'm the only programmer here and I'm only a junior programmer). Thank you in advance for taking the time to look and help!


Solution

  • Function arguments are passed by value, not by reference. So assigning to bool doesn't modify myBool.

    You should have the function return the new value, and you can reassign it to the variable.

    let myBool = false;
    
    function buttonToggle(bool, button) {
      bool = !bool;
      if (bool) {
        button.style.color = 'green';
      } else {
        button.style.color = 'white';
      }
      return bool;
    }
    <button class="js-myBtn" onclick="myBool = buttonToggle(myBool, this)">TOGGLE</button>