I'm trying to show and hide divs as the user clicks the button. I wanna change the image source of the button too, but my head is already exploding. So, one thing at time.
I know how to hide and show the divs one by one, but I'm struggling trying to automate the process.
Here's a screenshot of the page (mobile version): Here I am!
The buttons have two classes:
class="button button_0"
class="button button_1"
and so on
Here are the iD model of the divs:
answer_0
answer_1
and so on
The main.js:
const buttonList = document.querySelectorAll('.button');
const iconList = document.querySelectorAll(".icon");
const div = document.querySelectorAll('.container__answer');
const imgArray = ["assets/images/icon-minus.svg", "assets/images/icon-plus.svg"];
//functions
function changeImgSource () {
if (idIcon.src.match(imgArray[0])) {
idIcon.src = imgArray[1];
} else if (idIcon.src.match(imgArray[1])) {
idIcon.src = imgArray[0];
}
}
function showHide () {
if (idAnswer.style.display === "none") {
idAnswer.style.display = block;
} else {
idAnswer.style.display = none;
}
}
function all () {
showHide ();
changeImgSource ();
}
//i dont know :,(
let count = 0;
//I'll change to "for". Just think it's easier to read as a js newbie.
while (count < buttonList.length) {
const button = buttonList[count];
const classButton = button.classList[1];
const idIcon = `#icon_${classButton}`;
const idAnswer =`#answer_${classButton}`;
button.onclick = function () {
showHide(idAnswer);
}
count++;
}
Here's the GitHub Project. Is a free FrontEnd Mentor challenge, so I don't think there's a problem sharing. GitHub Project
As the Opera's console kept repeating the "idAnswer" was undefined, I tried to change the code's order. But it, at least alone, didn't help much.
At the end, Opera's inspector kept reapeating the message: "Uncaught TypeError: Cannot read properties of undefined (reading 'display')"
I've tried some fancier codes too, but I didn't understand much and didn't work at the end.
My advice is to not use IDs and instead use closest() and querySelector(). That way, it's extendable and reusable. This also leads you to be using classes to manage the show/hide rather than setting style properties directly (like style.display='block'). Here I am just coloring the cell, but you could easily change this to a show hide situation. Here's an example