ColorPicker Example -- Source Code

HTML Page -- index.htm

<!DOCTYPE html>

<!-- ColorPicker Example 
Source code file: index.htm -->

<html lang="en">
    <head>
        <meta content="text/html; charset=utf-8" 
              http-equiv="Content-Type">
        <title>ColorPicker Example</title>
        <link rel="stylesheet" href="styles.css">
        <script src="script.js"></script>
    </head>
    <body>
        <h1>ColorPicker Example</h1>

        <label for="cp">
            Pick color with colorpicker input element:
        </label><br><br>
        <input type="color" id="cp"><br><br>

        <!-- Submit form with method POST. 
             input fields with type=hidden are submitted
             to server, even though they are not visible
             on the form. -->
       <form id="form1"
             action="http://ectweb.cs.depaul.edu/sjost/receipt.php"
             method="POST">
           <input type="text" id="hex" name="hex"><br><br>
           <input type="hidden" id="red" name="red">
           <input type="hidden" id="green" name="green">
           <input type="hidden" id="blue" name="blue">
           <input type="submit" value="Submit Form">
        </form>
    </body>
</html>

CSS Sheet -- styles.css

/* Styles for ColorPicker Example 
   Source code file: styles.css */

body { background-color: #E0E0FF; 
       color: #000080; 
       font-family: Tahoma, Verdana, sans-serif; }
h1 { color: #800000; }

JavaScript Script -- script.js

// ColorPicker Example
// Source code file: script.js

function getColorComponents( ) {
    var hexColorCode = document.querySelector("#cp").value;
    var hex = document.querySelector("#hex");
    hex.value = hexColorCode;

    // parseInt with radix 16 converts a hex string to decimal.
    var r = parseInt(hexColorCode.slice(1, 3), 16);
    var g = parseInt(hexColorCode.slice(3, 5), 16);
    var b = parseInt(hexColorCode.slice(5, 7), 16);
    document.querySelector("#red").value = r;
    document.querySelector("#green").value = g;
    document.querySelector("#blue").value = b;
}

function init( ) {
    var cp = document.querySelector("#cp");
    cp.addEventListener("change", getColorComponents)
}