Feed on
Posts
Comments

Sometimes my ideas for jQuery plugins come from the need to solve a particular problem. Other times I see something done one way, and want to do it another way. Still other times they just come out of thin air. The inspiration for my latest plugin? Well, it came from a regular old, ugly checkbox.

I’m working on an application that has a lot of forms, and on some of the forms there are options that are simply yes/no or on/off. Now ordinarily I’d just slap a checkbox on the page and be done with it. In terms of functionality nothing is easier. A checkbox has two states, check or unchecked (although CSS3 will let us tap into an indeterminate state — but that’s not important right now). If the checkbox is checked, the option is selected; if not, it isn’t. Pretty basic. But from a design perspective, using a single checkbox to indicate whether something is on or off is well, pretty mundane. So I began to think, what could I do to improve upon the look while retaining the simplicity of a checkbox?

I don’t own an iPhone and probably won’t until Verizon gets them. I have, however, seen some of the iPhone’s interface and it’s obvious that UI (user interface) is where Apple excels. The wi-fi setting screen for the iPhone (and iPod touch and probably the iPad) has a great light switch style button that you can slide to turn  wi-fi on or off . Perfect! This button has the exact same functionality as a HTML checkbox. That’s all I needed to start me on developing this plugin.

Before I began to develop the plugin, I searched around to make sure I wasn’t going to be reinventing the wheel (always a good idea). Styling checkboxes (and radio buttons) using JavaScript isn’t something new, so I figured someone at some point did something similar. As it turns out, the closest thing I found was http://widowmaker.kiev.ua/checkbox/. This was very close to what I had envisioned, yet it didn’t quite fit the bill exactly. This plugin was a bit jerky and I wanted to use some basic animation effects to make it look smooth. I also wanted to make it more configurable. Finally, since this project hasn’t been updated in over a year, instead of trying to pickup from where this developer left off I decided to start fresh.

But once I began to develop a plugin to accomplish this idea, I thought that it may not be very useful if it only worked on individual checkboxes. So I decided it should be able to work on any number of checkbox and radio buttons. Now handling checkboxes via JavaScript is pretty easy. They stand alone and don’t depend on other elements. Radio buttons however are a different story. Radio buttons exist in groups of other radio buttons, all of which share the same name attribute. This makes things a little trickier. But in the end I created an easy to use plugin that changes any checkbox or radio button to an on/off, yes/no, true/false, binary call-it-what-you-want switch. I call this plugin LightSwitch because that’s the closest thing in the real world I could think of that resembled this plugin.

This plugin can be applied to any checkbox or radio button and the image used can be different whenever you call the plugin. For example, you could use the same image for all of your buttons, use one image for checkboxes and another for radio buttons, or apply a different image to each element individually. Since explaining this doesn’t have the same impact as using it, please check out the demos for a complete understanding. Oh, and since I wrote a post about using the <label> tag in forms, I thought it was only fitting to make sure that this plugin worked with labels too.

So why the name lightswitch? Because radioandcheckboxprettifier plugin doesn’t roll of the tongue.

Download

Download jquery.lightswitch.zip (13K – mostly images)

Demos

  • Example 1 – The most basic example.
  • Example 2 – Radio buttons with a default option  checked.
  • Example 3 – Checkboxes, some using label tags.
  • Example 4 – Multiple groups of radio buttons, some with label tags and a special toggle button that displays the actual radio buttons alongside the plugin buttons.
  • Example 5 – The whole shebang including radio buttons, checkboxes, labels, and disabled buttons. Pressing the submit button shows what options have been selected.

One note about the demos. I created all the button images myself and you are free to use them. Note that I don’t claim to be any kind of graphics whiz, so feel free to substitute my images with your own. Also, note that each switch image uses an overlaying ‘switchplate’ image which is used to mask part of the switch.

How to Use

You don’t need to do anything to your existing checkboxes or radio buttons (sweet!). To use the plugin you’ll need to have a copy of jQuery, or point to jquery on Google, and the plugin. Place the files on your site and link to them:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="jquery.lightswitch.js"></script>
<script type="text/javascript">
$(function(){
	$('input').lightSwitch();
});
</script>

That’s it! You can apply the lightswitch to any number of radio buttons and checkboxes on a page. View the examples for just a few ways.

Options

The following options are configurable:

  • animSpeed – the number of milliseconds it takes for the switch to change from one state to the other (default: 120)
  • hoverSpeed – the number of milliseconds it should take the switch to complete the peek animation when mouseing over a switch (default: 100)
  • switchImg – the path to your switch image (default: ‘switch.png’)
  • switchImgCover – the path to the switch plate image: (default: ‘switchplate.png’)
  • switchImgCoverWidth – width of the cover plate image (default: ’63px’)
  • switchImgCoverHeight – height of the cover plate image (default: ’18px’)
  • disabledImg – the path to the disabled image (default: ‘disabled.png’)
  • onShift – the CSS background-position of the on state (default: ’0px 0px’)
  • offShift – the CSS background-position of the off state (default:’-37px 0px’)
  • peekOff  the CSS background-position of the peek off state (default: ‘-6px 0px’)
  • peekOn – the CSS background-position of the peek on state (default: ‘-31px 0px’)

Note that the images, dimensions, and background-position options are all dependent on the images you use.Options are added when calling the script:

$('input:[name="radio1"]').lightSwitch({
    switchImg:'switch-1.png',
    animSpeed:250
});

Enjoy!

47 Responses to “New jQuery LightSwitch Plugin”

  1. Keith says:

    Nice! Although the graphics are, like you said, a little on the weak side – especially compared to Apple’s awe-inspiring UI element design. If you do feel the need, you should check out some of the PSD GUI templates of the iPad/iPhone ( http://www.teehanlax.com/blog/2010/02/01/ipad-gui-psd/ ). If I can find the time I would love to fork off a jQuery UI theme-based variation. Anyways, good stuff man.

  2. Miguel says:

    Thanks, another good post… your blog never disappoints :)
    In the demo at the top, right after clicking the lightswitch, if i press PgUp or PgDn, the lightswitch moves up and down.

  3. Cagil Seker says:

    That’s great way to spice up a UI. I think it works best when there are 4 or less choices as a group. Thanks for the great contribution…

  4. Elijah Manor says:

    Nice Plugin…

    Example #1 doesn’t work in the latest dev build of Google Chrome 5.0.396.0 dev

    There is a chance that it is one of my Chrome extensions.

  5. Thanks for developing , very useful

  6. bruce says:

    hi – great plug in ive just about cracked its use with round buttons and tick boxes with new graphics. very easy to use, thanks you.
    one question , does your script put a single white pixel in each corner of the image to round its edge? my images are dark grey on top of dark grey background, and with varying degrees of consistancy, i get these annoying little spots of white at each corner of every image. i guess if the background was white as in your examples i wouldnt notice!

  7. bruce says:

    just checked again – i guess the images are not on a transparent background, so will make some new ones – no prob! thanks again

  8. bruce says:

    sorry, like a bad penny ive bounced back – i tried putting a dark patch in the corners, but the whit single pixels are back in each corner, so i guess its something in the JS?

  9. Bill says:

    The switch images are one png and there’s another ‘switchplate’ png that sits on top of the switch images. Yes, it gives the switch it’s rounded appearance since it slides back and forth.

  10. this is cool! thanks for developing this!

  11. Juan says:

    I am working on a dynamic PowerPoint builder. A feature is to allow the end user to select from anarray of images on a page. I have been using a fieldset jquery to check all that I

    $(function () {
    $(‘#checkall’).click(function () {
    $(this).parents(‘fieldset:eq(0)’).find(‘:checkbox’).attr(‘checked’, this.checked);
    });
    });

    Can you help?

  12. Steve says:

    FYI: The peek/click functionality appears to not work in Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3.

    Works great in Safari 5 (Mac) though.

    • Steve says:

      Scratch that. The demo works in Safari 3.6.3 (Mac). Must be something in my code since I am having to init the function as an ajax callback. Sorry about that.

  13. Jimmy says:

    Dude,

    Love the plugin, have it working fairly nicely, however, I want them to display inline. I’ve tried to put them in a UL and make the li’s display inline, but I haven’t been able to force them with my will :(

    What can I do to make them appear in a row?

    Thanks,

    Jimmy

  14. Jimmy says:

    Nevermind, figured it out. If you put them into a UL with, for example, the name “options”, you could do this:

    #options li {
    width: 60px;
    float: left;
    margin: 0 20px 0 0;
    }

    The float takes care of the issue and the margin/width make it so they don’t overlap. Good times for all :)

  15. Jimmy says:

    Also, if you want to target each button for separate images, a good way to do that is to target by id instead of by name. Because the name has to be the same for the grouping to remain intact, id works as an alternate.

    $(function(){

    $(‘input:[id="Lite"]‘).lightSwitch({
    switchImg:’images/lite-buy.png’,
    });
    $(‘input:[id="Standard"]‘).lightSwitch({
    switchImg:’images/standard-buy.png’,
    });
    $(‘input:[id="Premium"]‘).lightSwitch({
    switchImg:’images/premium-buy.png’,
    });

    });

  16. Jeremy says:

    I seem to be having an issue with the style attribute not being applied to the element in jQuery 1.4.3+. Particulary, this select does not return an element: “$(‘+ span.switch’, this)”

  17. Renaud says:

    The verion 1.0.0 seems to have issues with jquery 1.4.3 1.4.4. Any idea what’s wrong? Any fix/update?
    Thanks,

  18. how do u use this as a button i can get the image to change button when i click it it doesn’t act like a button.

  19. NEVERMIND!!!! I FIGURED IT OUT!!!

  20. is there any way to make the slider default at no when the page loads?

  21. scott says:

    onChange doesnt work, how do you have make it work with onChange?

    • Gavin says:

      I’m quite weak on JQuery and Javascript. I have a drop down that un-hides a checkbox if a particular option is selected, then if it is checked, another on appears. the select and the first checkbox have an onchange link to a Javascript function to trigger the appearance of the next checkbox.

      Enabling lightSwitch seems to kill the onchange event for any element it is applied to?

  22. Scott says:

    if i set the checked box to checked via this lightswitch it move the image and marks it as checked, when i validate some other data on the page and result of that validation leads me to setting the above mention checked box to NOT checked, the image doesnt return to NO/OFF/False until i mouse over (not click just mouse over) is there a way to make the image move with the mouse over?

  23. admin says:

    I just released version 1.0.1 to account for the changes in jQuery 1.4.4. Grab it from the downloads tab.

  24. BigDirty says:

    IE8 is throwing an error:

    Webpage error details

    User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)
    Timestamp: Mon, 20 Dec 2010 13:18:19 UTC

    Message: Syntax error
    Line: 1
    Char: 1
    Code: 0
    URI: http://www.catchmyfame.com/?live-comment-preview.js

    Message: Invalid argument.
    Line: 156
    Char: 295
    Code: 0
    URI: http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js

    Message: Invalid argument.
    Line: 156
    Char: 295
    Code: 0
    URI: http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js

    Message: Invalid argument.
    Line: 156
    Char: 295
    Code: 0
    URI: http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js

  25. BigDirty says:

    Working with jquery 1.4.2 but not 1.4.4 Even your site is throwing this error in IE8.

    BTW – Awesome work dude, very good indeed :)

Trackbacks/Pingbacks

  1. [...] Catch My Fame » New jQuery LightSwitch Plugin Posted May 10th, 2010 in Blog by Gareth http://www.catchmyfame.com/2010/05/07/new-jquery-lightswitch-plugin/ [...]

  2. [...] Catch My Fame » New jQuery LightSwitch Plugin (tags: forms jquery ui) [...]

  3. [...] For another take on this, see the jQuery LightSwitch plugin. [...]

Leave a Reply

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>