HTML DOM addEventListener() Method
As time goes on it appears that this Event handler technique is key to the manipulation of the DOM.
The code is in the Javascript that "feeds" the Accordion functionality that I was using on my Site Map and other pages. I have expanded on my analysis of the accordian
Events can be added to many DOM ELements, other places where I have seen this on pages that feature on this website are the page search example and the accessibilty code for the carousel
The syntax of the addEventListener() method are shown below and there is significance to the Bubbling and Capturing of the events - this is especially relevant to the example below. Or maybe not as I was assuming that the Bubbling and Capturing were handled by the return value of the function - there is no third parameter in that example.
However, there is a discussion related to the third parameter
The Javascript code taken from the accordian example:
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";
}
});
}
I was using the accordian on my Javascript page where I was attempting to look and try to understand the code.
The "event" is added to elements of an array "acc[i]" that is the contents of the accordian button. The contents of the accordian button is a div with the class="panel". The panel div is the element after the button element and therefore the nextSiblng. It contains the text from the section to be expanded. The "selctor?" nextElementSibling is used as this returns the next sibling node as an element node (i.e. it ignores the text and comment nodes)
The click is added as an event (note: "click" as oppssed to "onClick")and an "anonymous function" is used as the seconed parameter.
There is no third (optional) parameter, the useCapture parameter as the event handler is required to be executed during the bubbling phase.
The this.classList.toggle bit toggles the panel from non active to active.
The syntax is:
document.addEventListener(event, function, useCapture)
Where:
The useCapture parameter of addEventListener()
This is explained in more detail on the MDN pages.
For a practical example of the handling of events in both the Capturing and Bubbling phases please see my page on the accordian.
There is a LOT going on in the script for the accordian - I have tried to explain it here
The third parameter of addEventListener()
This is also explained in more detail on the MDN pages.