Mobile Web Wearable Web

CSS Color Module Level 3: Specifying Color and Opacity

This tutorial demonstrates how you can manage colors in your application.

Warm-up

Become familiar with the CSS Color Module Level 3 API basics by learning about:

Creating a Color Generator

To enhance the user experience of your application, you must learn to create a HSLA color generator to set the color value for an element in the HSLA format.

Figure: HSLA color generator

HSLA color generator

  1. To create the color generator, define 2 <div> elements for displaying the HSLA value as text and in a color box. You also need 4 slider inputs for defining the HSLA color:
    • The first input has a range of 0 - 360 and represents hue.
    • The second and third inputs have a range of 0 - 100 and represent saturation and lightness.
    • The last input has a range of 0 - 10 and represents alpha transparency.

      The range should be 0.1 - 1, but the minimum value of the min attribute is 0 so the value can be divided by 10.

    <div id="color-generator">
       <div id="text-box"></div>
       <div id="color-box"></div>
    
       <label>Hue</label>
       <input id="hue" value="0" type="range" min="0" max="360">
    
       <label>Saturation</label>
       <input id="saturation" value="100" type="range" min="0" max="100">
    
       <label>Lightness</label>
       <input id="lightness" value="50" type="range" min="0" max="100">
    
       <label>Alpha</label>
       <input id="alpha" value="10" type="range" min="0" max="10">
    </div>
    
  2. Obtain the values from the slider inputs with the getElementById method. Remember to divide the alpha value by 10 to reach the correct range of 0.1 - 1.
    var h = document.getElementById('hue').value,
        s = document.getElementById('saturation').value,
        l = document.getElementById('lightness').value,
        a = document.getElementById('alpha').value / 10;
    
  3. Set the HSLA text and the color of the color box by defining the color from the inputs in the HSL and HSLA formats.

    If the alpha is 1, the HSL format is displayed. Otherwise, the HSLA format is used.

    /* Define formats */
    hsl = 'hsl(' + h + ', ' + s + '%, ' + l + '%)';
    hsla = 'hsla(' + h + ', ' + s + '%, ' + l + '%, ' + a + ')';
    
    /* Set the color of the box */
    cBox = document.querySelector('#color-box'),
    
    /* Set the text */
    tBox = document.querySelector('#text-box');
    
  4. Add an event handler to the input sliders to change the displayed text and color box color when the slider values change.
    var inputs = document.querySelectorAll('#color-generator input[type=range]');
    			
    for (i = 0; i < inputs.length; i++)
    {
       inputs[i].onchange = function()
       {
          /* Show color */
       }
    }
    

Source Code

For the complete source code related to this use case, see the following file:

Go to top