I'm trying to link from one page on my website to content in an accordion on another page, and I can't get the javascript to work for opening that accordion automatically. I've looked at a lot of other questions on here about the issue, and tried several things, but it seems like most of them pertain to people using jQuery or bootstrap, which I am not.
The most baffling part is that I actually DID get it to work yesterday with the script below, but when I tried to utilize the same script for other anchors, it broke completely. Even after I took the additional anchors out, the original still doesn't work anymore. I'm very new to javascript so the answer may be something obvious--I've been thinking it might have to do with calling or invoking the function in the script? But that's just a guess.
Thank you in advance to anyone who can help!
Here is the html for the link:
<a href="/projects#stripmall"><p><b>Strip Mall Magazine, <i>Issue 02: Fall 2024.</i></b></p></a>
and the javascript, anchor within the accordion menu and CSS for the accordion as a whole, and the function to open the correct section:
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", function() {
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.display === "block") {
panel.style.display = "none";
} else {
panel.style.display = "block";
}
});
//Function to open accordion from link
document.addEventListener("load", function() {
function openAccordionByHash() {
var hash = window.location.hash;
if (hash) {
var target = document.querySelector(hash); // matching the hash
if (target && target.classList.contains("panel")) {
this.classList.toggle("active");
}
}
}
});
}
.accordion {
background-color: transparent;
color: black;
padding: 5px;
width: 100%;
border: none;
text-align: center;
outline: none;
font-size: 16pt;
font-family: "space grotesk";
display: block;
transition: 0.4s;
cursor: pointer;
}
.active,
.accordion:hover {
color: inherit;
}
.panel {
display: none;
background-color: white;
overflow: hidden;
padding-left: 15px;
padding-top: 10px;
;
}
<button class="accordion"><div class="button">Strip Mall Magazine</div></button>
<div id=stripmall class="panel">
panel content goes here
</div>