Open In App

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

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:



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: 






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

Example 2: 




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


Article Tags :