Working with input type color in HTML5

The input type=color is one of the new input types of the HTML5. This input type allows the user to select a color with the help of color picker and returns the hexadecimal value for the selected color. You will see how to use and how to get the value of the selected color in the Example 1. You can also check the functionality in the Demo section, where you can change the background and border of the div tag. Try the Demo.

The simple declaration of this in HTML as shown below:

<input type="color">

You can also predefined the value of it like as:

<input id="bordercolor" type="color" value="#ff8000">

Demo

Choose a color for Background :

Choose a color for Border :

Choose a color for Text :

Welcome

[Example1]

In the following example we can change the background color and border color of the div element. You can also change the fore color of the text inside the div(See the above demo).

<!DOCTYPE html>
<html>
<head>
    <title>Example of the HTML5 color input tag</title>
 
    <script>
        function ChangeBackground() {
            document.getElementById("targetdiv").style.backgroundColor =
             document.getElementById("background").value;
        }
        function ChangeBorderColor() {
            document.getElementById("targetdiv").style.borderColor =
             document.getElementById("bordercolor").value;
        } 
        function ChangeTextColor() {
            document.getElementById("spantext").style.color =
             document.getElementById("textcolor").value;
        }
    </script>
 
    <style>
        .demo span{width: 200px;display: block;}
        #targetdiv{float: left; width: 250px; height: 250px; 
             border: 2px solid #ff8000;background-color: #ffffc6;}
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div class="demo">
        <div style="float: left; width: 220px">
 
            <span>Choose a color for Background :</span>
            <input id="background" type="color" value="#ffffc6" 
                    onchange="ChangeBackground();" /><br /><br />
 
            <span>Choose a color for Border :</span>
            <input id="bordercolor" type="color" value="#ff8000" 
                   onchange="ChangeBorderColor();" /><br /><br />
 
            <span>Choose a color for Text :</span>
            <input id="textcolor" type="color" value="#ff0080"
                   onchange="ChangeTextColor();" />
 
        </div>
        <div id="targetdiv">
           <span id="spantext" style="font-size:28px;color:#ff0080;
               font-weight: bold;margin: 50px 0 0 60px;">Welcome</span>
        </div>
    </div>
    </form>
</body>
</html>