Split Button with Dropdown Template
Combine a default action and a set of related options into one compact, versatile control.
A split button is perfect for actions like "Save," where a dropdown can reveal less common options like "Save As" or "Export."
About the Split Button with Dropdown
A split button is a hybrid control that builds on the standard dropdown button. It provides a primary action that can be executed with a single click, while also giving users access to a list of secondary commands in an attached dropdown menu. This prevents the most common action from being hidden away inside a menu, greatly improving efficiency and discoverability.
Features
- Efficient UX: Gives one-click access to the main action, with secondary actions neatly tucked away.
- Accessible by Design: The dropdown toggle correctly uses
aria-haspopup="true"and a togglingaria-expandedattribute to communicate its state to assistive technologies. The menu itself hasrole="menu". - Smart Dropdown Behavior: The JavaScript ensures the dropdown closes if the user clicks anywhere outside of the component.
- Self-Contained: The HTML, CSS, and JavaScript work together as a single, copy-pasteable component.
Code Breakdown
The component consists of a container div, a primary action button, and a second button that serves as the dropdown toggle. Below them is a hidden ul which acts as the menu.
The JavaScript logic adds a click event listener to the dropdown toggle. When clicked, it toggles an is-open class on the container and updates the button's aria-expanded attribute. The CSS uses this class to show or hide the menu. A second event listener is attached to the document to detect clicks outside the component, ensuring the menu closes when it's no longer being used.
Code
Here is the complete code for the split button component.