What am I doing wrong? Any idea how to make this accordion menu work?
I’ve been trying to figure out why my accordion menu for a Frontend Challenge isn’t working. It’s currently throwing the following error:
Uncaught TypeError: Cannot read properties of undefined (reading ‘toggle’) at HTMLButtonElement.<anonymous>
This error is from Google dev tools. My active
class is defined in my css file. I’m trying to make it toggle between two classes when my button is active but I haven’t been able to activate it or toggle it at all.
Can someone help me get an idea of what’s going on?
These are snippets of my code.
const acc = document.getElementsByClassName("accordion_btn");
var i;
for (let i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", (event) => {
this.classList.toggle("active");
this.classList.toggle("accordion_btn:hover");
const panel = this.nextElementSibling;
if (panel.style.display === "block") {
panel.style.display = "none";
} else {
panel.style.display = "block";
}
});
}
.accordion_btn {
width: 100%;
background-color: hsl(0, 0%, 100%);
text-align: left;
border: none;
outline: none;
margin: 20px 0;
transition: 0.4s;
}
.accordion_btn:hover {
background-color: hsl(276, 51%, 90%);
}
.active {
background-color: red;
}
.panel {
font-weight: 400;
color: hsl(292, 16%, 49%);
display: none;
overflow: hidden;
margin-bottom: 20px;
text-align: left;
}
<div class="accordion">
<button class="accordion_btn">
What is Frontend Mentor, and how will it help me?
</button>
<div class="panel">
<p> Frontend Mentor offers...</p>
</div>
</div>
<div class="accordion">
<button class="accordion_btn">
Is Frontend Mentor free?
</button>
<div class="panel">
<p>Yes, Frontend Mentor...</p>
</div>
</div>
<div class="accordion">
<button class="accordion_btn">
Can I use Frontend Mentor projects in my portfolio?
</button>
<div class="panel">
<p>Yes...</p>
</div>
</div>
<div class="accordion">
<button class="accordion_btn">
How can I get help if I'm stuck on a Frontend Mentor challenge?
</button>
<div class="panel">
<p>The best place to...</p>
</div>
</div>
</div>
I tried changing my variable declarations with var
and const
but that probably has nothing to do with it? I also tried adding defer to my script tag in my original HTML file.
2
Answers
Because
this
is pointing at the window object not your current accordion.So you simply just need to change every
this
toacc[i]
.For more information about
this
keyword I recommend reading this reference this-JavaScript | MDNHere is the working code
don’t use arrow function,then you can the this;
like this;