Skip to content
Related Articles

Related Articles

Improve Article
How to change an element color based on value of the color picker value using onclick?
  • Difficulty Level : Medium
  • Last Updated : 20 Sep, 2019

We can define color picker by input type=”color”. It provides a user interface element that lets a user specify a color, either by using a visual color picker interface or by entering the color into a text field in #rrggbb hexadecimal format. Only the colors without alpha channel are allowed. Though CSS colors have more formats, e.g. color names, functional notations and a hexadecimal format with an alpha channel.

Approach:

  • To change the color of our element based on the value of color picker we have to use onclick() event of the element and change its CSS color property as per the selected value in color picker element.
  • This value appears as color picker’s value attribute. using javascript, we will change the color of our element as the chosen value in color picker.

Syntax:

  • HTML:
     < div id="elementId" onclick="fn_name()"></div>
          < input name="ColorPickerId" type="color" id="ColorPickerName" />
  • JavaScript:
    document.getElementById("elementID").style.Color = 
          document.getElementById("ColorPickerId").value;

Example 1:




<html>
  
<head>
    <style>
        #Myelement {
            background-color: black;
            width: 500px;
            height: 100px;
        }
    </style>
</head>
  
<body>
    <div id="Myelement" 
         onclick="changeColor()">
  </div>
    <input name="MyColorPicker"
           type="color"
           id="MyColorPicker" />
    <script>
        function changeColor() {
            document.getElementById(
              "Myelement").style.backgroundColor =
                document.getElementById(
              "MyColorPicker").value;
        }
    </script>
</body>
  
</html>

Output:
Before:

After picking the color:

After clicking the div:

Example 2:




<html>
  
<head>
</head>
  
<body>
    <h1 id="Myelement" 
       onclick="changeColor()">
        GeeksforGeeks
    </h1>
    <input name="MyColorPicker" 
           type="color"
           id="ColorPicker1" />
    <script>
        function changeColor() {
            document.getElementById("Myelement").style.color =
                document.getElementById("ColorPicker1").value;
        }
    </script>
</body>
  
</html>

Output:
Before:

After picking the color:

After clicking the div:




My Personal Notes arrow_drop_up
Recommended Articles
Page :