HomeLanguagesJavascriptHow to change an element color based on value of the color...

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:

  • 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()">
    neveropen
</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?

RELATED ARTICLES

Most Popular

Dominic
32688 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
7057 POSTS0 COMMENTS
Nicole Veronica
12198 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12293 POSTS0 COMMENTS
Shaida Kate Naidoo
7182 POSTS0 COMMENTS
Ted Musemwa
7447 POSTS0 COMMENTS
Thapelo Manthata
7160 POSTS0 COMMENTS
Umr Jansen
7150 POSTS0 COMMENTS