RSS

Turn jQuery slider into a switch

28 May

jQuery slider
jQuery slider

Three simple steps to turn jQuery UI slider into a switch.

1. Create HTML structure of the slider:

<span id="slider">
    <label id="on">GapAd ON<img src="/media/images/vsep.png"></label>
    <label id="off">GapAd OFF<img src="/media/images/vsep.png"></label>
</span>

2. Initialise jQuery slider object with two positions – on (zero) and one (off). And assign a handler for “slide” event that will change slider image depending on switch state.

$( "#slider" ).slider({
    value: 0,
    min: 0,
    max: 1,
    step: 1,
    slide: function( event, ui ) {
        if (ui.value == 0) {
            $('.ui-slider-handle').css('backgroundImage','url(/media/images/on.png)');
        } else {
            $('.ui-slider-handle').css('backgroundImage','url(/media/images/off.png)');
        }
    }
});

3. Now make a slider look a bit more like a switch with use of some CSS:

#slider {
    width: 170px; 
    background: #d6d5d5; 
    height: 3px; 
    position: relative; 
    display: block; 
}
	   
#slider .ui-slider-handle {
    top: -16px; 
    background: url('/media/images/on.png') 0 0 no-repeat; 
    border: 0; 
    width: 35px; 
    height: 35px; 
    left: 20px;
}
	
/* styling for the labels */    
#slider #on { position: absolute; ... }
#slider #off {position: absolute; ... }

In the end you should get something like on the picture in the beginning of the post.

Advertisements
 
2 Comments

Posted by on May 28, 2011 in CSS

 

Tags: , ,

2 responses to “Turn jQuery slider into a switch

  1. John

    July 16, 2011 at 5:00 pm

    Great post, I think I am going to use this as an interview question for new developers.

     
  2. Dasha Salo

    July 16, 2011 at 6:25 pm

    Just don’t tell them it was my idea 😀

     

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: