Use your left/right keys to browse tutorials
jQuery Fancy Switch

jQuery Fancy Switch

1 Star2 Stars3 Stars4 Stars5 Stars
Posted on November 24, 2011

I wrote a post a while back on coding an iPhone style switch using jQuery. I’ve now put together a simple tutorial demonstrating how simple it is to build a switch that triggers two radio buttons in a field set. It also degrades gracefully if JavaScript is disabled just displaying the two radio buttons with labels. This tutorial is aimed at users just stepping on the jQuery ladder, and hopefully this will demonstrate how simple some techniques are. The design of the switch was done by Shegy and you can download the full set of switch designs as a PSD here

The Code

Lets run through line by line the JavaScript. The first three lines after the DOM ready function are setup incase the user has JavaScript disabled. So if enabled we display the switch background image and hide the radio buttons as well as indent the text on the labels.

We’ve then setup a ‘change()’ function which means the function is executed each time the user selects either checkbox, we then check the value of the radio button thats been selected and adjust the background position of the sprite image.

Lastly for demo purposes im just displaying the status of the radio buttons in the div with the class ‘result’


	$('.switch').css('background', 'url("switch.png")');
	$('.on, .off').css('text-indent','-10000px');

    $("input[name=on_off]").change(function() {
      var button = $(this).val();
		if(button == 'off'){ $('.switch').css('background-position', 'right'); }
		if(button == 'on'){ $('.switch').css('background-position', 'left'); }	 
		 $('.result span').html(button); 




Here we have a simple form with the two radio buttons in a fieldset.

<form action="" method="get">

<fieldset class="switch">
    <label class="off">Off<input type="radio" class="on_off" name="on_off" value="off"/></label>
    <label class="on">On<input type="radio" class="on_off" name="on_off" value="on"/></label>

<input type="submit" value="Submit"/>


<div class="result">The button is: <span>on</span></div>



	background:left no-repeat;

.on, .off{



More tutorials from Papermashup
  • Lakshay Dulani

    Hi..the button is really good.. I was looking for a button that has a neutral state as well.. as in neither on nor off..Its better to give this feature