Javascript toggle menu

Many site owners want to let users toggle different sections of a web page. Often this is both unnecessary and annoying for the site visitors, but it can sometimes be useful for hiding otherwise distracting content.

This toggle menu is made with HTML, CSS and Javascript. I also have a CSS toggle menu that uses no Javascript, but I much prefer the Javascript version on this page: it's more intuitive to use, its buttons are synchronized, and it should be supported by older browser versions.

Browser support

Should work in IE9 and other newer browsers.

Demo

Section A

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna...

Section B

...aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.

How it works

The script toggles sections and synchronizes button texts automatically.

Without Javascript all section content is visible. No non-functional buttons will appear.

Keyboard navigation (Tab key and spacebar) is supported. To help keyboard users even more, let the checkboxes stay visible.

Installation

Multiple toggle containers can be used on the same page.

The button text can be edited in the data-show-label and data-hide-label custom attributes.

The buttons are created with LABEL elements, containing INPUT checkboxes. To work with keyboard navigation, the checkboxes can't be hidden with CSS display: none;. Instead, use opacity: 0; to hide them, and position: absolute; (without offsets) to prevent them from affecting content flow.

The visible SECTION elements can be styled with the .show_toggle_section selector in the stylesheet.

published: Dec 15, 2015
last modified: Jan 26, 2017