Toggle Show/Hide Multiple Elements With Pure JavaScript
This is for when you need to toggle between showing and hiding more than one element on a page. For example, click a heading to show a list underneath it, then click again to hide the list. This uses pure JavaScript, no jQuery or other libraries. (See this instead for an example using jQuery.)
You want the event listener to apply to many items, for example, to all the h2
elements on the page. You don’t need to add the event listener multiple times to each element. You add the event listener once, which checks if an h2
element was clicked.
Here is a working example. In this example, the h2
headings have the class "clickable-heading"
.
See more: toggle
Lj
September 14th, 2015 at 3:32 am
How about horizontal like main menu with toggle show/hide?
Alex
June 24th, 2019 at 5:09 pm
Thanks so much, by far the simplest and most effective explanation I’ve found for this.