Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds

Building a Color Picker with Hex RGB Conversion

Save for later
  • 18 min read
  • 02 Mar 2015

article-image

In this article by Vijay Joshi, author of the book Mastering jQuery UI, we are going to create a color selector, or color picker, that will allow the users to change the text and background color of a page using the slider widget. We will also use the spinner widget to represent individual colors. Any change in colors using the slider will update the spinner and vice versa. The hex value of both text and background colors will also be displayed dynamically on the page.

(For more resources related to this topic, see here.)


This is how our page will look after we have finished building it:
building-color-picker-hex-rgb-conversion-img-0

Setting up the folder structure


To set up the folder structure, follow this simple procedure:

  1. Create a folder named Article inside the MasteringjQueryUI folder.
  2. Directly inside this folder, create an HTML file and name it index.html.
  3. Copy the js and css folder inside the Article folder as well.
  4. Now go inside the js folder and create a JavaScript file named colorpicker.js.


With the folder setup complete, let's start to build the project.

Writing markup for the page


The index.html page will consist of two sections. The first section will be a text block with some text written inside it, and the second section will have our color picker controls. We will create separate controls for text color and background color. Inside the index.html file write the following HTML code to build the page skeleton:

<html>
<head>
<link rel="stylesheet" href="css/ui-lightness/jquery-ui-
1.10.4.custom.min.css">
</head>
<body>
<div class="container">
<div class="ui-state-highlight" id="textBlock">
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim
ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex
ea commodo
consequat. Duis aute irure dolor in reprehenderit in
voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint
occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id
est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim
ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex
ea commodo
consequat. Duis aute irure dolor in reprehenderit in
voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint
occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id
est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim
ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex
ea commodo
consequat. Duis aute irure dolor in reprehenderit in
voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint
occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id
est laborum.
</p>
</div>
<div class="clear">&nbsp;</div>
<ul class="controlsContainer">
<li class="left">
<div id="txtRed" class="red slider" data-spinner="sptxtRed"
data-type="text"></div><input type="text" value="0" id="sptxtRed"
data-slider="txtRed" readonly="readonly" />
<div id="txtGreen" class="green slider" dataspinner="
sptxtGreen" data-type="text"></div><input type="text"
value="0" id="sptxtGreen" data-slider="txtGreen" readonly="readonly"
/>
<div id="txtBlue" class="blue slider" dataspinner="
sptxtBlue" data-type="text"></div><input type="text"
value="0" id="sptxtBlue" data-slider="txtBlue" readonly="readonly" />
<div class="clear">&nbsp;</div>
Text Color : <span>#000000</span>
</li>
<li class="right">
<div id="bgRed" class="red slider" data-spinner="spBgRed"
data-type="bg" ></div><input type="text" value="255" id="spBgRed"
data-slider="bgRed" readonly="readonly" />
<div id="bgGreen" class="green slider" dataspinner="
spBgGreen" data-type="bg" ></div><input type="text"
value="255" id="spBgGreen" data-slider="bgGreen" readonly="readonly"
/>
<div id="bgBlue" class="blue slider" data-spinner="spBgBlue"
data-type="bg" ></div><input type="text" value="255" id="spBgBlue"
data-slider="bgBlue" readonly="readonly" />
<div class="clear">&nbsp;</div>
Background Color : <span>#ffffff</span>
</li>
</ul>
</div>
<script src="js/jquery-1.10.2.js"></script>
<script src="js/jquery-ui-1.10.4.custom.min.js"></script>
<script src="js/colorpicker.js"></script>
</body>
</html>


We started by including the jQuery UI CSS file inside the head section. Proceeding to the body section, we created a div with the container class, which will act as parent div for all the page elements. Inside this div, we created another div with id value textBlock and a ui-state-highlight class. We then put some text content inside this div. For this example, we have made three paragraph elements, each having some random text inside it.

After div#textBlock, there is an unordered list with the controlsContainer class. This ul element has two list items inside it. First list item has the CSS class left applied to it and the second has CSS class right applied to it.

Inside li.left, we created three div elements. Each of these three div elements will be converted to a jQuery slider and will represent the red (R), green (G), and blue (B) color code, respectively. Next to each of these divs is an input element where the current color code will be displayed. This input will be converted to a spinner as well.

Let's look at the first slider div and the input element next to it. The div has id txtRed and two CSS classes red and slider applied to it. The red class will be used to style the slider and the slider class will be used in our colorpicker.js file. Note that this div also has two data attributes attached to it, the first is data-spinner, whose value is the id of the input element next to the slider div we have provided as sptxtRed, the second attribute is data-type, whose value is text. The purpose of the data-type attribute is to let us know whether this slider will be used for changing the text color or the background color.

Moving on to the input element next to the slider now, we have set its id as sptxtRed, which should match the value of the data-spinner attribute on the slider div. It has another attribute named data-slider, which contains the id of the slider, which it is related to. Hence, its value is txtRed.

Similarly, all the slider elements have been created inside div.left and each slider has an input next to id. The data-type attribute will have the text value for all sliders inside div.left. All input elements have also been assigned a value of 0 as the initial text color will be black.

The same pattern that has been followed for elements inside div.left is also followed for elements inside div.right. The only difference is that the data-type value will be bg for slider divs. For all input elements, a value of 255 is set as the background color is white in the beginning.

In this manner, all the six sliders and the six input elements have been defined. Note that each element has a unique ID.

Finally, there is a span element inside both div.left and div.right. The hex color code will be displayed inside it. We have placed #000000 as the default value for the text color inside the span for the text color and #ffffff as the default value for the background color inside the span for background color.

Lastly, we have included the jQuery source file, the jQuery UI source file, and the colorpicker.js file.

With the markup ready, we can now write the properties for the CSS classes that we used here.

Styling the content


To make the page presentable and structured, we need to add CSS properties for different elements. We will do this inside the head section. Go to the head section in the index.html file and write these CSS properties for different elements:

<style type="text/css">
  body{
    color:#025c7f;
    font-family:Georgia,arial,verdana;
    width:700px;
    margin:0 auto;
  }
  .container{
    margin:0 auto;
    font-size:14px;
    position:relative;
    width:700px;
    text-align:justify; 
  }
#textBlock{
    color:#000000;
    background-color: #ffffff;
  }
  .ui-state-highlight{
    padding: 10px;
    background: none;
  }
  .controlsContainer{
      border: 1px solid;
      margin: 0;
      padding: 0;
      width: 100%;
      float: left;
  }
  .controlsContainer li{
      display: inline-block;
      float: left;
      padding: 0 0 0 50px;
      width: 299px;
  }
  .controlsContainer div.ui-slider{
      margin: 15px 0 0;
      width: 200px;
      float:left;
  }
  .left{
    border-right: 1px solid;
  }
  .clear{
    clear: both;
  }
 
  .red .ui-slider-range{
background: #ff0000;
}
  .green .ui-slider-range{
background: #00ff00;
}
  .blue .ui-slider-range{
background: #0000ff;
}
 
  .ui-spinner{
      height: 20px;
      line-height: 1px;
      margin: 11px 0 0 15px;
    }
  input[type=text]{
    margin-top: 0;
    width: 30px;
  }
</style>


First, we defined some general rules for page body and div .container. Then, we defined the initial text color and background color for the div with id textBlock.

Next, we defined the CSS properties for the unordered list ul .controlsContainer and its list items. We have provided some padding and width to each list item.

We have also specified the width and other properties for the slider as well. Since the class ui-slider is added by jQuery UI to a slider element after it is initialized, we have added our properties in the .controlsContainer div .ui-slider rule.

To make the sliders attractive, we then defined the background colors for each of the slider bars by defining color codes for red, green, and blue classes.

Lastly, CSS rules have been defined for the spinner and the input box.

We can now check our progress by opening the index.html page in our browser. Loading it will display a page that resembles the following screenshot:
building-color-picker-hex-rgb-conversion-img-1

It is obvious that sliders and spinners will not be displayed here. This is because we have not written the JavaScript code required to initialize those widgets. Our next section will take care of them.

Implementing the color picker


In order to implement the required functionality, we first need to initialize the sliders and spinners. Whenever a slider is changed, we need to update its corresponding spinner as well, and conversely if someone changes the value of the spinner, we need to update the slider to the correct value. In case any of the value changes, we will then recalculate the current color and update the text or background color depending on the context.

Defining the object structure


We will organize our code using the object literal. We will define an init method, which will be the entry point. All event handlers will also be applied inside this method.

To begin with, go to the js folder and open the colorpicker.js file for editing. In this file, write the code that will define the object structure and a call to it:

var colorPicker = {
  init : function ()
  {
   
  },
  setColor : function(slider, value)
  {
  },
  getHexColor : function(sliderType)
  {
  },
  convertToHex : function (val)
  {
  }
}
 
$(function() {
  colorPicker.init();
});


An object named colorPicker has been defined with four methods. Let's see what all these methods will do:

  • init: This method will be the entry point where we will initialize all components and add any event handlers that are required.
  • setColor: This method will be the main method that will take care of updating the text and background colors. It will also update the value of the spinner whenever the slider moves. This method has two parameters; the slider that was moved and its current value.
  • getHexColor: This method will be called from within setColor and it will return the hex code based on the RGB values in the spinners. It takes a sliderType parameter based on which we will decide which color has to be changed; that is, text color or background color. The actual hex code will be calculated by the next method.
  • convertToHex: This method will convert an RGB value for color into its corresponding hex value and return it to get a HexColor method.


This was an overview of the methods we are going to use. Now we will implement these methods one by one, and you will understand them in detail.

After the object definition, there is the jQuery's $(document).ready() event handler that will call the init method of our object.

The init method


In the init method, we will initialize the sliders and the spinners and set the default values for them as well. Write the following code for the init method in the colorpicker.js file:

Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at €18.99/month. Cancel anytime
  init : function ()
{
  var t = this;
  $( ".slider" ).slider(
  {
    range: "min",
    max: 255,
    slide : function (event, ui)
    {
      t.setColor($(this), ui.value);
    },
    change : function (event, ui)
    {
      t.setColor($(this), ui.value);
    }
  });
 
  $('input').spinner(
  {
    min :0,
    max : 255,
    spin : function (event, ui)
    {
      var sliderRef = $(this).data('slider');
      $('#' + sliderRef).slider("value", ui.value);
    }
  });
 
 
  $( "#txtRed, #txtGreen, #txtBlue" ).slider('value', 0);
  $( "#bgRed, #bgGreen, #bgBlue" ).slider('value', 255);
}


In the first line, we stored the current scope value, this, in a local variable named t.

Next, we will initialize the sliders. Since we have used the CSS class slider on each slider, we can simply use the .slider selector to select all of them. During initialization, we provide four options for sliders: range, max, slide, and change. Note the value for max, which has been set to 255. Since the value for R, G, or B can be only between 0 and 255, we have set max as 255. We do not need to specify min as it is 0 by default.

The slide method has also been defined, which is invoked every time the slider handle moves. The call back for slide is calling the setColor method with an instance of the current slider and the value of the current slider. The setColor method will be explained in the next section.

Besides slide, the change method is also defined, which also calls the setColor method with an instance of the current slider and its value.

We use both the slide and change methods. This is because a change is called once the user has stopped sliding the slider handle and the slider value has changed. Contrary to this, the slide method is called each time the user drags the slider handle. Since we want to change colors while sliding as well, we have defined the slide as well as change methods.


It is time to initialize the spinners now. The spinner widget is initialized with three properties. These are min and max, and the spin. min and max method has been set to 0 and 255, respectively. Every time the up/down button on the spinner is clicked or the up/down arrow key is used, the spin method will be called. Inside this method, $(this) refers to the current spinner. We find our related slider to this spinner by reading the data-slider attribute of this spinner. Once we get the exact slider, we set its value using the value method on the slider widget.

Note that calling the value method will invoke the change method of the slider as well. This is the primary reason we have defined a callback for the change event while initializing the sliders.


Lastly, we will set the default values for the sliders. For sliders inside div.left, we have set the value as 0 and for sliders inside div.right, the value is set to 255.

You can now check the page on your browser. You will find that the slider and the spinner elements are initialized now, with the values we specified:
building-color-picker-hex-rgb-conversion-img-2

You can also see that changing the spinner value using either the mouse or the keyboard will update the value of the slider as well. However, changing the slider value will not update the spinner. We will handle this in the next section where we will change colors as well.

Changing colors and updating the spinner


The setColor method is called each time the slider or the spinner value changes. We will now define this method to change the color based on whether the slider's or spinner's value was changed. Go to the setColor method declaration and write the following code:

setColor : function(slider, value)
{
  var t = this;
  var spinnerRef = slider.data('spinner');
  $('#' + spinnerRef).spinner("value", value);
 
  var sliderType = slider.data('type')
 
  var hexColor = t.getHexColor(sliderType);
  if(sliderType == 'text')
  {
      $('#textBlock').css({'color' : hexColor});
      $('.left span:last').text(hexColor);               
  }
  else
  {
      $('#textBlock').css({'background-color' : hexColor});
      $('.right span:last').text(hexColor);               
  }
}


In the preceding code, we receive the current slider and its value as a parameter. First we get the related spinner to this slider using the data attribute spinner. Then we set the value of the spinner to the current value of the slider.

Now we find out the type of slider for which setColor is being called and store it in the sliderType variable. The value for sliderType will either be text, in case of sliders inside div.left, or bg, in case of sliders inside div.right. In the next line, we will call the getHexColor method and pass the sliderType variable as its argument. The getHexColor method will return the hex color code for the selected color.

Next, based on the sliderType value, we set the color of div#textBlock. If the sliderType is text, we set the color CSS property of div#textBlock and display the selected hex code in the span inside div.left. If the sliderType value is bg, we set the background color for div#textBlock and display the hex code for the background color in the span inside div.right.

The getHexColor method


In the preceding section, we called the getHexColor method with the sliderType argument. Let's define it first, and then we will go through it in detail. Write the following code to define the getHexColor method:

getHexColor : function(sliderType)
{
  var t = this;
  var allInputs;
  var hexCode = '#';
  if(sliderType == 'text')
  {
    //text color
    allInputs = $('.left').find('input[type=text]');
  }
  else
  {
    //background color
    allInputs = $('.right').find('input[type=text]');
  }
  allInputs.each(function (index, element) {
    hexCode+= t.convertToHex($(element).val());
  });
 
  return hexCode;
}


The local variable t has stored this to point to the current scope. Another variable allInputs is declared, and lastly a variable to store the hex code has been declared, whose value has been set to # initially.

Next comes the if condition, which checks the value of parameter sliderType. If the value of sliderType is text, it means we need to get all the spinner values to change the text color. Hence, we use jQuery's find selector to retrieve all input boxes inside div.left. If the value of sliderType is bg, it means we need to change the background color. Therefore, the else block will be executed and all input boxes inside div.right will be retrieved.

To convert the color to hex, individual values for red, green, and blue will have to be converted to hex and then concatenated to get the full color code. Therefore, we iterate in inputs using the .each method. Another method convertToHex is called, which converts the value of a single input to hex. Inside the each method, we keep concatenating the hex value of the R, G, and B components to a variable hexCode. Once all iterations are done, we return the hexCode to the parent function where it is used.

Converting to hex


convertToHex is a small method that accepts a value and converts it to the hex equivalent. Here is the definition of the convertToHex method:

convertToHex : function (val)
{
  var x  = parseInt(val, 10).toString(16);
  return x.length == 1 ? "0" + x : x;
}


Inside the method, firstly we will convert the received value to an integer using the parseInt method and then we'll use JavaScript's toString method to convert it to hex, which has base 16. In the next line, we will check the length of the converted hex value. Since we want the 6-character dash notation for color (such as #ff00ff), we need two characters each for red, green, and blue. Hence, we check the length of the created hex value. If it is only one character, we append a 0 to the beginning to make it two characters. The hex value is then returned to the parent function.

With this, our implementation is complete and we can check it on a browser. Load the page in your browser and play with the sliders and spinners. You will see the text or background color changing, based on their value:
building-color-picker-hex-rgb-conversion-img-3

You will also see the hex code displayed below the sliders. Also note that changing the sliders will change the value of the corresponding spinner and vice versa.

Improving the Colorpicker


This was a very basic tool that we built. You can add many more features to it and enhance its functionality. Here are some ideas to get you started:

  • Convert it into a widget where all the required DOM for sliders and spinners is created dynamically
  • Instead of two sliders, incorporate the text and background changing ability into a single slider with two handles, but keep two spinners as usual

Summary


In this article, we created a basic color picker/changer using sliders and spinners. You can use it to view and change the colors of your pages dynamically.

Resources for Article:





Further resources on this subject: