Checkbox.js aims to create a functional checkbox out of pretty much any HTML markup. This allows you to style the checkbox any way you would like. It gives you full control of the markup.
Getting started
Given our HTML:
Subscribe?
We can create a new checkbox out of a span by passing the element to checkbox.js:
document;
This will create a checkbox out of that HTMLElement that you
passed. Checkbox.js will try to find a label
element in the DOM to
associate with the checkbox. If it can't find a label
it will throw
an error. All checkboxes must have a label.
What your checkbox should look like after using checkbox.js:
Subscribe?
Passing a label directly
If you would like you can pass a reference to the label directly to checkbox.js:
Subscribe?
documentlabel: document;
Setting the initial state
You can also initialize the checkbox to be checked by default by
passing a isChecked
key in the options
object.
Subscribe?
documentlabel: documentisChecked: true;
Programmatically change state
If you store a reference to the checkbox when you instantiate it, you
can call methods on that instance like toggleCheckbox
. This allows
you to toggle the checkbox from actions other than a click or keyboard
event.
Subscribe?
// init an unchecked checkboxlet checkbox = document;checkbox; // toggles to checked