An Accordian in HTML
This is a revision of my analysis of the accordian code.
Since my intitial review I have worked out a lot more about what is going on. There is some pretty advanced, well I think so, CSS and DOM manipulation going on here. The containers that contain the text which is displayed when they are expanded have a control structure that features the addition of eventListeners to "this" instances of the DOM elements.
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.maxHeight){
panel.style.maxHeight = null;
} else {
panel.style.maxHeight = panel.scrollHeight + "px";
}
});
}
What is going on here.
The accordian is built as button element and a div [.panel] (that seems to be associated with the accordian object). The button is styled by css to look like a bar that spans the whole width of its container. The button-bar has a pseudo-element (a plus symbol) that displays on the right of the button-bar.
The variable acc is an HTML Collection, an array-like list. This array-like list is then traversed and eventListeners are added to each of the array-list items. The anonymous function also toggles the array-like items to "active". The .panel style is also changed to give it the appropriate height.
panel.style.maxHeight = panel.scrollHeight + "px";
The .panel container is also animated to slowly open and close, ease-in and out, to show that it is actually animated.
What was not working
When I moved the CSS and the JavaScript from the original example into external files (accordian.css and script.js) I did not really understand that the script shown above needs to be on the same page as the accordian. This is to say that they cannot be all linked from external files but the addition of a second event handler to the button resulted in a double click to expand the panels.
The script as it was presented by the W3C example accesses the elements on the page that the accordian resides. A different way of accessing the panel elements probably can be developed. The accordian that the W3.css library provides uses a different technique of displaying the expandable elements, this bears further investigation.