pepe
pepe

Reputation: 9909

Dropdown selector to change color of DIV using JS and CSS

What I need is a simple color picker (max 6-8 color) so the user can choose a color for an event that will be entered in a calendar.

I have tested several jQuery colopicker plugins and none have worked well in my project.

Either they are too complex (like Farbtastic) or are simple but don't run on the most recent version of jQuery.

So I decided to provide a good ol' dropdown menu with a list of colors

<select id="evt_color"> 
<option value="#3366CC">Blue</option> 
<option value="#E070D6">Fuchsia</option> 
<option value="#808080">Gray</option> 
<option value="#4bb64f">Green</option> 
<option value="#ed9d2b">Orange</option> 
<option value="#FF9CB3">Pink</option> 
<option value="#EA4A4A">Red</option> 
</select>

This works well. But I would like to give the user some feedback on the color they choose, before submitting the form.

I wonder if somehow we could create a small square DIV next to the dropdown, and have its background-color change to the value of the selected color onChange, via something like getElementById or other method. By default, the first color would be selected (Blue).

Anyone have suggestions for this? jQuery or raw JS suggestions are welcome!

Thanks for helping!

Upvotes: 2

Views: 4986

Answers (1)

karim79
karim79

Reputation: 342635

$(document).ready(function() {
    $("#evt_color").change(function() {
        $("#someDiv").css("background-color", $(this).val());
    }).change(); // trigger change event so div starts out with a colour
                 // on page load
});

You can try it here.

Upvotes: 5

Related Questions