Tuesday, September 15, 2009

jQuery Slider UI Control Tutorial: RGB Color Picker with Hex Converter

In my first tryst with jQuery (A lightweight JavaScript library that emphasizes interaction between JavaScript and HTML.) I thought of building a tool which I use a lot during web designing for converting RGB color values to Hex and vise versa. jQuery's provides a lot of nifty visual controls which can be used with a lot of ease. I used the Slider UI control for this tool which lets you choose the values like regular Windows slider control. For more information and documentation on jQuery Slider Control, visit http://docs.jquery.com/UI/Slider.

This is how a basic jQuery Slider looks like:

jQuery Slider UIAnd do you want to know how much it takes to include such a basic Slider UI on your page? You’ll be surprised I bet...
HTML Code inside your Body:
<div id="slider"></div>

JavaScript Code to instantiate the Slider when the Page loads:
<script type="text/javascript">
  $(document).ready(function(){
    $("#slider").slider();
  });
</script>

Wasn’t that just a piece of cake? Yes it was, thanks to the folks who developed jQuery which gives us a hassle free coding environment with rich web development tools.

Now it’s time to build our RGB to Hex color conversion tool and learn the jQuery Slider UI Control in depth. We’ll have to use three sliders here to pick Red, Green and Blue color values and calculate Hex values and vise versa. I have also customized the Slider Handles to display the current slider value inside it. I have borrowed the color conversion functions from http://www.javascripter.net. The values and background color on the page changes dynamically as the user would slide the handles for choosing color values.

This is how my RGB Color Picker looks like:
jQuery Slider User Interface: RGB Color Picker with Hex Converter

For using the Slider UI you’ll have to include the UI CSS and other JavaScript libraries on your page from http://jqueryui.com. I have also created my own styles for the Sliders and its Handles. The JavaScript code for this tool is explained below:

  • $(document).ready(function(){...}); function is used to initialize the Slider UI Controls when the page loads for the first time. You can instantiate the controls individually by using $("#R"),$("#G"),$("#B") wrappers also, but I have used a common wrapper with all the div tags having sliders class $("div.sliders"). The Sliders are instantiated with min and max values from 0 to 255, step increment of 1, animation enabled to slide handle smoothly when user click outside handle on the bar, and assigned UpdateColor function to slide and change events. For more information and documentation on the Slider UI Control, visit http://docs.jquery.com/UI/Slider.
  • UpdateColor() function is used to get the latest values ($('#R').slider('option', 'value');) from the individual sliders and update the page background colors, slider handle values, and other values on page with conversion to Hex value.
  • HEXtoRGB() function is triggered when the user wants to convert Hex value (from text field) to RGB. The Hex value is first validated then assigned to the individual Sliders after conversion to R, G and B values respectively. UpdateColor() function is called again to update all the values on the page.

Here is the complete HTML page code for the Color Converter Slider Control:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery Slider Control: RGB Color Picker</title>
<link type="text/css" href="http://jqueryui.com/latest/themes/base/ui.all.css" rel="stylesheet" />
<script type="text/javascript" src="http://jqueryui.com/latest/jquery-1.3.2.js"></script>
<script type="text/javascript" src="http://jqueryui.com/latest/ui/ui.core.js"></script>
<script type="text/javascript" src="http://jqueryui.com/latest/ui/ui.slider.js"></script>
<style type="text/css">
.sliders { margin: 20px 20px 20px 0px; width: 500px;}
.handle {
      font-family: Verdana, Geneva, sans-serif;
      font-size: x-small;
      text-decoration: none;
      text-align: center;
      padding-top: 3px;
}
.box {
      width: 250px;
      border: solid 1px #000;
      padding: 5px;
      background-color:#FFF;
}
h1 {
      padding: 10px;
      margin: 0px;
      background-color: #FFF;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
      //initialize Slider Controls
      $("div.sliders").slider({ animate: true , min: 0, max: 255, step: 1, slide: UpdateColor, change: UpdateColor});
    UpdateColor(); //Update the Colors and Values on the Page
});
function UpdateColor(){
      var R = $('#R').slider('option', 'value'); //Get R Value from Slider
      var G = $('#G').slider('option', 'value'); //Get G Value from Slider
      var B = $('#B').slider('option', 'value'); //Get B Value from Slider
      var HexValue = RGBtoHex(R,G,B); //Calculate Hex values from R,G,B
      $('body').css("background-color", "#" + HexValue); //Set page background color
      $('#values').html("<b>R:</b>"+R+" <b>G:</b>"+G+" <b>B:</b>"+B+" | <b>Hex:</b> #"+HexValue); //Display Values
      $('#Rh').html(R); $('#Gh').html(G); $('#Bh').html(B); //Update R,G,B values on the slider handles
      $('#Hex').val(HexValue); //Update value in the Hex text field
}
function HEXtoRGB(){
      var Hex = $("input#Hex").val(); //Get Hex value from text field
      var HexReg = /^([a-fA-F0-9]{6})$/; //Hexadecimal value validation regular expression
      if(HexReg.test(Hex)==false){ alert("Invalid Hex Code"); return false; } //Validate Hex Value
      $('#R').slider('option', 'value', HexToR(Hex)); //Update R Slider Value
      $('#G').slider('option', 'value', HexToG(Hex)); //Update G Slider Value
      $('#B').slider('option', 'value', HexToB(Hex)); //Update B Slider Value
      UpdateColor(); //Update the Colors and Values on the Page
}

//Color conversion functions from http://www.javascripter.net
function RGBtoHex(R,G,B) {return toHex(R)+toHex(G)+toHex(B)}
function toHex(N) {
 if (N==null) return "00";
 N=parseInt(N); if (N==0 || isNaN(N)) return "00";
 N=Math.max(0,N); N=Math.min(N,255); N=Math.round(N);
 return "0123456789ABCDEF".charAt((N-N%16)/16) + "0123456789ABCDEF".charAt(N%16);
}
function HexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}
function HexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}
function HexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}
function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}
</script>
</head>

<body>
<h1>RGB Color Picker using jQuery Slider</h1>
<div id="R" class="sliders"><a id="Rh" style="left: 0%; width:25px; height:16px; " class="handle ui-slider-handle" href="#"></a></div>
<div id="G" class="sliders"><a id="Gh" style="left: 0%; width:25px; height:16px; " class="handle ui-slider-handle" href="#"></a></div>
<div id="B" class="sliders"><a id="Bh" style="left: 0%; width:25px; height:16px; " class="handle ui-slider-handle" href="#"></a></div>
<div class="box">
<div id="values"></div>
<br /><strong>Hex Value:</strong> #<input name="Hex" type="text" id="Hex" size="6" maxlength="6" /><input type="button" value="Update" onclick="HEXtoRGB()" />
</div>
</body>
</html>

I hope this tutorial was simple enough to cover all the important aspects regarding the jQuery Slider UI Control. You can refer the documentation (http://docs.jquery.com/UI/Slider) for extra information on options, events and methods to play around with it.

1 comment:

Thanks a lot for your valuable comments :)