skip to Main Content

I’m using a switch statement to determine which button is being pressed, they both work with the same function when changing the documents background color, however, when I pass in the actual element and target it within the function and attempt to change it’s background color nothing is happening.

Changing the background color of the actual document works fine, but changing the background color of elements passed into the function is not working.

<div class="gender-toggle">
        <div class="toggle">
          <div id="male-toggle">
            <p>Male</p>
          </div>
          <div id="female-toggle">
            <p>Female</p>
          </div>
        </div>
</div>
const maleToggle = document.getElementById('male-toggle').addEventListener('click', changeGenderClick);
const femaleToggle = document.getElementById('female-toggle').addEventListener('click', changeGenderClick);

function changeGenderClick(event){
  const genderId = event.target.id;
  switch(genderId){
    case 'male-toggle':
      changeGender(femaleToggle);
      break;
    case 'female-toggle':
      changeGender(femaleToggle);
    break;
  }
}

function changeGender(currentGender){
  currentGender.style.backgroundColor = 'red';
};

2

Answers


  1. You’re not passing the #male-toggle element. You’re passing the return value of .addEventListener which is undefined. Split the declaration and the event listener assignment to two separate rows:

    const maleToggle = document.getElementById('male-toggle');
    
    maleToggle.addEventListener('click', changeGenderClick);
    

    Do the same thing to #female-toggle.


    For accessibility, use radio-buttons. If you do that, then you don’t need specific javascript to toggle between the genders, and you can use CSS to style the radio-button based on if it’s :checked or not.

    Login or Signup to reply.
  2. Aside from your mistakes with assigning maleToggle and femaleToggle, and using femaleToggle twice, there is a fair canonical way to do this: Remove from elements that should no longer have the style, then add it to the element that was selected

    var change = (event) => {
      let f = document.querySelector(".foo");
      if (f) f.classList.remove("foo");
      event.target.classList.add("foo");
    }
    
    document.querySelectorAll(".toggle > div").forEach((e) => e.addEventListener("click", change));
    .foo {
      background-color: red;
    }
    <div class="gender-toggle">
            <div class="toggle">
              <div id="male-toggle">
                <p>Male</p>
              </div>
              <div id="female-toggle">
                <p>Female</p>
              </div>
            </div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search