checkbox-util

A utility to enable easier use of checkboxes as triggers for CSS.


Keywords
css, js, checkbox, utilities
License
ISC
Install
npm install checkbox-util@0.1.3

Documentation

checkbox-util

by Vidur Butalia

This utility is designed to solve usability issues that may result from using a checkbox & labels as a 'hack' for CSS-only interactivity.

Its main function is to enable keyboard focus on labels and allow them to be triggered by keypresses, since the default 'magic label' behaviour only triggers the associated checkbox input on click. This is inadequate if you desire your interactive component to be keyboard-friendly.

A secondary function also provided, similarly meant for the checkbox & label design pattern, lets you automatically make elements tabbable based on the state of the checkbox.

The function exported is as follows:

function checkboxUtil(selector, labelTabindex, inputTabindex, keycodes, focusElements)

where the parameters are as follows:

selector: HTML selector to find labels for, defaults to input[type=checkbox]

labelTabindex: If true, sets the tabIndex for all labels to 0, i.e. enables keyboard focus on labels

inputTabindex: If true, sets the tabIndex for all inputs to -1, i.e. disables keyboard focus on labels

keycodes: Custom keycode(s) to trigger input click on, defaults to 32 (spacebar)

focusElements: If true, checks the <input>'s data attribute for a selector, whose elements to make tabbable when the checkbox is checked. The attribute is 'data-tab-hide-selector' and any valid HTML selector is allowed.

Do note that you may wish to set tabIndex to 0 manually in your markup rather than use this function to set it dynamically. Similarly, you may wish to disable focus completely on the elements visible when the checkbox is checked in markup, rather than relying on this utility to dynamically enable and disable keyboard focus on them.