Two-state button with HTML, CSS and jQuery

To express 0-1 state checkboxes are mostly used in websites. A two-state button used instead can be a bit more nicer and interesting. You can create it in HTML, CSS and Javascript/jQuery quite easy. Here, is how to do this.

We need:

  • a checkbox and a label folowing it,
  • some styling in CSS,
  • a piece of code in Javascript/jQuery.

You can put checkbox (<input type="checkbox"/>) and label directly in HTML:

<input id="chk" type="checkbox"/>
<label id="lbl" for="chk" title="Auto">A</label>

or generate it dynamically with jQuery:

var where = $('#main').find("form");

$("<input />",
{
    type: "checkbox",
    id: 'chk',
    checked: false
}).appendTo(where);

$("<label></label>",
{
    "for": 'chk',
    text: 'A',
    id: 'lbl',
    title: 'Auto!'
}).appendTo(where);

Where where holds some div or any other elements, containing some form, to which you want to add this two-state button.

Now, we need some styling to hide checkbox (yes!) and style label like a button:

#lbl {background-color: #dddddd; display: inline-block; height: 20px; text-align: center; width: 20px; border-top: solid 1px white; border-left: solid 1px white; border-right: solid 1px #bbbbbb; border-bottom: solid 1px #bbbbbb}
#chk {display: none;}
#chk:checked + #lbl {border-top: solid 1px #bbbbbb; border-left: solid 1px #bbbbbb; border-right: solid 1px white; border-bottom: solid 1px white}
   

Here is the key. We use borders in different colors (top + left versus bottom + right) to mimic button look.

All we need else is a piece of jQuery code to react on button (label) click:

var onCheckboxChangeHandler: function(e)
{
    var checked = !$('#chk').is(":checked");

    console.log(checked);
}

We need to negate value read from checkbox for reasons described in this post.

We also need to bind this function as an event, somewhere in the code:

$('#lbl').on("click", self.onCheckboxChangeHandler);

Now, everything should work fine.

BTW: I called this event onCheckboxChangeHandler, not onLabelClickHandler, because, though label is clicked (checkbox remains hidden), checkbox itself is an element, which state is being changed and which value is read.

Leave a Reply