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"
.
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.
Alex
March 2nd, 2021 at 6:49 pm
Hello! that was a nice tutorial, very good
Isabel
March 5th, 2021 at 7:47 pm
Thank you.
jasvinder
March 31st, 2021 at 3:40 am
when i an using this code it dint work and sowing this error in console
Uncaught TypeError: Cannot read property ‘style’ of null
at HTMLDocument.toggleDocs
Eric
April 17th, 2021 at 4:15 am
Hi,
actually there is a way to do that in HTML 5 with no script at all :
it’s the “details” tag. With a 96% support, that is now my preferred method for toggling elements.
here’s an example with custom styling:
Compatibility :
IE : no,
Edge : 79+,
Firefox 49+,
Chrome 12+,
Safari : 6+,
Opera : 15+,
Safari iOS: 6+,
Opera mini : no,
Android Browser: 4+,
Opera mobile: 62+,
Chrome Android : 89+
Firefox Android : 86+,
Samsung Internet : 4+,
QQ Browser: 104+,
Baidu Browser : 7.12+
KaiOS Browser : 2.5+
there is a js polyfill for anterior browsers (see on caniuse.com)
You can also add an event listener to do things on closing an opening
And the appearance can be customized with css : (this very ugly example from developer.mozilla.org/en-US/docs/Web/HTML/Element/details)
You can event customize the ► (see on the mozilla.org page)
Authorized User
June 9th, 2021 at 12:52 pm
This was exactly the simple solution I needed.
I don’t usually signup to post but resolved a lot of searching.
Thank you!
*spam email used of course :))