"Toggles" that control categories of toggle switches with intermediary state for when only some subitems are active.
- Using Light DOM allows you to style everything with regular CSS
- Checkboxes fallback (for items only, category toggles need JS to show up at all)
- No dependencies
https://codepen.io/nonsalant/pen/OPJLJoL
-
Grab the files from the
src
folder. -
Load the style and the main script (adjust the paths as needed):
<link rel="stylesheet" href="./src/toggle-categories.css">
<script src="./src/toggle-categories.js"></script>
- The script can also be loaded as a module:
<script src="./src/toggle-categories.js" type="module"></script>
- Use it like this:
<toggle-categories>
<ul>
<li>
<span>Category Name</span>
<ul>
<li><label><input type="checkbox"> Item 1</label></li>
<li><label><input type="checkbox"> Item 2</label></li>
</ul>
</li>
<li>
<span>Other Category Name</span>
<ul>
<li><label><input type="checkbox"> Item 3</label></li>
<li><label><input type="checkbox"> Item 4</label></li>
<li><label><input type="checkbox"> Item 5</label></li>
</ul>
</li>
</ul>
</toggle-categories>
- Use the
checked
attribute to have an item pre-selected:
<li><label><input type="checkbox" checked> Item</label></li>
- ID's are generated automatically for the checkboxes, but you can also set (some or all of) them manually:
<li><label><input type="checkbox" id="item-1"> Item 1</label></li>
You can override these CSS custom properties to change the appearance of the component by adding the following CSS anywhere:
toggle-categories ul {
--toggle-category-color: light-dark(red, hotpink);
--toggle-color: #018259;
--toggle-category-height: .8rem;
--toggle-height: 1rem;
--toggle-categories--heading-bg: light-dark(#ddd, #333);
--toggle-categories-bg: light-dark(#f0f0f0, #222);
}
Note: ul
added in the selector above for extra specificity, to override the values set in toggle-categories.css.
The setTimeout(()=>{...})
wrapping the insides of the connectedCallback()
lifecycle method allows the script to be used as a non-module script tag (in addition to the module option) from anywhere on the page, including the header, by adding a ~4ms delay which should be enough for the DOM to be ready.