I'm working on creating a collapsible menu that I can easily customize on any page without the use of iframes. As someone new to web design, I have knowledge of CSS and HTML but I am currently learning JavaScript with limited experience in jQuery or AJAX.
Below is the script I'm using for my collapsible menu:
var coll = document.getElementsByClassName("collapsible");
var i;
for (i = 0; i < coll.length; i++) {
coll[i].addEventListener("click", function() {
this.classList.toggle("active");
var content = this.nextElementSibling;
if (content.style.display === "block") {
content.style.display = "none";
} else {
content.style.display = "block";
}
});
}
.collapsible {
background: none;
cursor: pointer;
border: none;
text-align: left;
outline: none;
}
.content {
margin-left: 18px;
display: none;
overflow: hidden;
}
<div id="menu">
<button type="button" class="collapsible">Menu</button>
<div class="content">
<a href="link.html" class="menu">Option 1</a><br>
<a href="link2.html" class="menu">Option 2</a>
</div>
</div>
While this setup works smoothly, issues arise when loading the HTML content into the div using AJAX:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'menu.html', true);
xhr.onreadystatechange = function () {
if (this.readyState !== 4) return;
if (this.status !== 200) return;
document.getElementById('menu').innerHTML = this.responseText;
};
xhr.send();
The contents of "menu.html" are as follows:
<button type="button" class="collapsible">Menu</button>
<div class="content">
<a href="link.html" class="menu">Option 1</a><br>
<a href="link2.html" class="menu">Option 2</a>
</div>
Although the HTML loads correctly, the collapsible menus lose their functionality. Despite searching for solutions, I haven't found one that resolves the issue. Any assistance in identifying the cause and providing a fix would be greatly appreciated.