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
You’re not passing the
#male-toggle
element. You’re passing the return value of.addEventListener
which isundefined
. Split the declaration and the event listener assignment to two separate rows: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.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