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.

5 comments:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from Javascript Training in Chennai . or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry. ES6 Training in Chennai

    ReplyDelete
  2. mytectra placement Portal is a Web based portal brings Potentials Employers and myTectra Candidates on a common platform for placement assistance.

    ReplyDelete
  3. Guaranteed #1 Search Engine Ranking Supreme Free Viral Traffic Join Now Get Millions Of Hits Free To Your Site/Blog!

    PornKings Adult Shopping Backlinks-Shopping Mega Store Legendary Stars As Stormy Daniels,Shawna Edwards,Jenna Jamison-New Adult Stars Movies,Adult Toys,Enhancers,Merchandise-More !

    Hits Express Rotator System Do You Need Visitors to Your Website or Affiliate Program? If your looking to gain more visitors to your website Hits Express is your answer. With our program your site is being shown to people all over the world 24/7 365 days a year!

    PAYDIR Free For All Forum Portal Search Engine Crawled Network PR10 Ranking Information Forum XXX!

    FreeLinkExchanges Be Seen In 12 Nations 312 Sites Over 30 Millions Viewers Monthly Buy Featured Link Now With 150 Search Engines Crawling The Network!

    How do I get guaranteed traffic? When someone signs up from your site, they must first click on your classified ad which will open a new window leading to your main website. They will have to wait a few seconds for the code to appear on a separate frame at the top of the screen reach millions free now!

    Blast Your Ad to Over 23,000 Opt-in Prospects at ShowMyLinks Submit Your Solo Email Ad to All Showmylinks Members GET YOUR TEXT LINK ADs LISTED 100% FREE FOR LIFE PLUS EARN MONEY TO YOUR PAYPAL!!

    Adult Store Empires Backlinks Resources Search Engine XXX!

    GET YOUR OWN MONEY-MAKING AD BOARD -- Integrating Text ad, Banner Ad and Email Ad into one Portal Make Money Fast With Your Paypal Reach Million Dollars In A Year Fast !

    Full Length Homemade Videos Watch real people's private home sex videos. Forget about those shitty 1-2 minute clips, these are all high quality full length videos! 40+ Bonus Sites You will also get full access to the entire reelpass network of sites which features over 40+ awesome movie sites, 1000's of movies and pictures to download! Download, Burn & Share Not only do you get to watch all our movies, you can also download every single one and save it forever, burn them to dvd or share with friends!!

    ReplyDelete

Thanks a lot for your valuable comments :)