Pete_1
Pete_1

Reputation: 1011

basic javascript accordion

I am making an accordion FAQ. There are tons of scripts online, but I hate using scripts I don't understand (I'm new to Javascript). So I start from basic and work my way up. The following code is frustrating me as to why it doesn't work:

Javascript:

function faq1() {

var faq1 = document.getElementById("faq1")

if (faq1.style.display = "none") {
faq1.style.display = "block";
}

else {
faq1.style.display = "none";
}
}

HTML/CSS:

<a href="#" onclick="faq1()">Question 1</a>
<div id="faq1" style="display: none">
Answer to question 1
</div>

The script opens the accordion just find. However, the "else" portion of the Javascript doesn't work, when i click on the link a second time I can't get the display to turn back off. I have tried various methods of "else if's" to see if that would work with no luck.

Thanks guys

Upvotes: 1

Views: 2002

Answers (1)

alex
alex

Reputation: 490233

You are using assignment (=) instead of comparison (==) in your condition.

Alternatively,

function faq1() {

    var faq1 = document.getElementById("faq1");

    faq1.style.display = faq1.style.display == "none" ? "" : "none";

}

Upvotes: 6

Related Questions