#collapsable modal in js doesn't work

1 messages · Page 1 of 1 (latest)

lone kernel
#

Hi, I am making a list of questions and answers in js. I have created a class which creates a collapsible modal of question and answer. On click the answer div should change the style from display: "none" to display: "block". Somehow the function that toggles the answer doesn't apply the styles.

Below is my code:

import SvgIcon from "./SvgIcon";

class FAQItem {
constructor(question, answer) {
this.question = question;
this.answer = answer;
this.htmlElement = this.createComponent();
}

createComponent() {
const container = document.createElement("div");
container.classList.add("collapsible__container");

const questionElement = document.createElement("button");
questionElement.classList.add("question");

const questionText = document.createElement('h1');
questionText.textContent = this.question;
questionElement.appendChild(questionText);
container.appendChild(questionElement);

questionElement.addEventListener('click', () => this.toggleAnswer())

const answerElement = document.createElement("div");
answerElement.classList.add("answer");
answerElement.textContent = this.answer;

container.appendChild(answerElement);

return container;

}

toggleAnswer() {
const answer = this.htmlElement.querySelector(".answer");
const question = this.htmlElement.querySelector('.question');
question.classList.toggle('active');
answer.style.display = answer.style.display === "block" ? "none" : "block";
console.log(Toggled answer for question: ${this.question});

}
}

export default FAQItem;

I tried to many things, I have used chat gpt as well and I don't see anything wrong in my code, unless there is some issue of my styling which I haven't noticed. We can meet in voice chat so I can show my code if needed

sly shale
#

you can try instead of directly checking the answer.style.display property, you can use the window.getComputedStyle method to get the actual computed style

const answerDisplayStyle = window.getComputedStyle(answer).getPropertyValue('display');