+ 1

Can someone explain me this ACCORDION javascript code? [Solved]

Its like everyone is using this same piece of code for making accordion and i can't understand it. Can someone explain it. 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"; } }); }

27th Apr 2020, 2:13 PM
Shreyansh Gaurav
Shreyansh Gaurav - avatar
4 Answers
+ 4
(part 1/2) document.getElementsByClassName(class_id) return list of of all elements with 'class' attribute containing 'class_id' ("accordion" in your case) for loop initialization is done with 3 parts comma (;) separated declared in parenthesis: 1) todo once before start: i = 0; 2) condition to checked at each iteration end: i < acc.length 3) todo at each iteration end: i++ then, at each iteration the block wrapped in curly braces ({}) is executed. so in your case, for each element of the list of elements stored in 'acc' the code register a function to be called when user click on it: 1) element.addEventListener(event_name,callback_function) register the 'callback_function' to the 'event_name' ("click") of 'element' (acc[i]) 2) acc[i] access the element at index 'i' of the list 'acc' (description of 'callback_function in next post: ran out of chars ^^)
28th Apr 2020, 12:12 PM
visph
visph - avatar
+ 3
(part 2/2) in the 'callback_function': 1) this refer to the 'element' where the 'event_name' occurs ("click") 2) element.classList property refer to the 'class' attribute as a list(instead of a white-space separated string) 3) classList.toggle(class_id) switch 'class_id' ("active"): if present remove it else add it 4) element.nextElementSibling refer to the element just after the targeted 'element' (same parent: neighbour) and is stored to 'panel' variable (to shorthand write) 5) element.style refer to the inlined css 'style' attribute of 'element' ('panel' var) 6) if 'panel' have inlined css property 'display' equals to "block", then set it to "none", else set it to "block" (toggle/switch value between "block" or "none" -- ie: visible / invisible)
28th Apr 2020, 12:13 PM
visph
visph - avatar
0
Bro i love you. Thank you so much. I get it now. Thanks for your effort and writing it down so detailed. Thanks again brother. You are genius.
28th Apr 2020, 12:35 PM
Shreyansh Gaurav
Shreyansh Gaurav - avatar
0
Maybe could you set the best answer mark on my first post? ;)
28th Apr 2020, 12:52 PM
visph
visph - avatar