Open In App

How to change an element color based on value of the color picker value using onclick?

Improve
Improve
Like Article
Like
Save
Share
Report

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 colors without alpha channels 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 the color picker we have to use onclick() event of the element and change its CSS color property as per the selected value in the color picker element.
  • This value appears as the color picker’s value attribute. using javascript, we will change the color of our element as the chosen value in the color picker.

Syntax:

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

Example 1: 

html




<style>
    #Myelement {
        background-color: black;
        width: 500px;
        height: 100px;
    }
</style>
<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>


Output:

How to change an element color based on value of the color picker value using onclick?

How to change an element color based on value of the color picker value using onclick?

Example 2: 

html




<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>


Output:

How to change an element color based on value of the color picker value using onclick?



Last Updated : 23 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads