I've been struggling to troubleshoot an issue with a JavaScript accordion menu on my WordPress site. When I try to click the accordion button, it doesn't reveal the hidden content beneath it. I've attempted various solutions, but none have seemed to work for me as a beginner in this field. Here's the code I'm working with:
JavaScript:
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", function() {
/* Toggle between adding and removing the "active" class,
to highlight the button that controls the panel */
this.classList.toggle("active");
/* Toggle between hiding and showing the active panel */
var panel = this.nextElementSibling;
if (panel.style.display === "block") {
panel.style.display = "none";
} else {
panel.style.display = "block";
}
});
}
CSS:
/* Styling for buttons used to open and close the accordion panel */
.accordion {
background-color: #eee;
color: #444;
cursor: pointer;
padding: 18px;
width: 100%;
text-align: left;
border: none;
outline: none;
transition: 0.4s;
}
/* Adding background color when clicked or hovered over */
.active, .accordion:hover {
background-color: #ccc;
}
/* Style for the accordion panel - initially hidden */
.panel {
padding: 0 18px;
background-color: white;
display: none;
overflow: hidden;
}
HTML:
<button class="accordion">Section 1</button>
<div class="panel">
<p>Lorem ipsum...</p>
</div>
When using Firefox console, the error message TypeError: panel is null
is pointing to the line
if (panel.style.display === "block") {
. While testing with alert('hi');
, everything seems to be loading fine, so the problem may lie within that specific piece of code.