Open In App
Related Articles

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

Improve Article
Improve
Save Article
Save
Like Article
Like

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?


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 23 Jan, 2023
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials