This tutorial is to see how to do simple color picker using jQuery. In a previous tutorial, we have seen date picker by using jQuery UI Library. There are various jQuery plugins providing color picker feature. This tutorial gives a simple example code as a guideline to start writing your own jQuery color picker plugin.
In this example, we are using CSS selectors to show color palette. On clicking each color in the palette we store the selected color into a pointer to be applied to the target DIV. We are using jQuery CSS function to pick and apply colors to the target DIV.
This is the HTML code for showing color palette to pick colors. It shows four colors with separate DIV tags.
<div class="circular-div" id="aquamarine" onClick="pickColor(this.id);"></div>
<div class="circular-div" id="bisque" onClick="pickColor(this.id);"></div>
<div class="circular-div" id="yellow" onClick="pickColor(this.id);"></div>
<div class="circular-div" id="aqua" onClick="pickColor(this.id);"></div>
<div id="target" onClick="applyColor();">Click to Apply Color</div>
<div id="pointer"></div>
And the styles are,
<style type="text/css">
#pointer {
position: absolute;
top: 0;
left: 0;
height: 20px;
width: 20px;
border:#000 1px solid;
border-radius:50%;
}
.circular-div{padding:20px;width:25px;height:200px;float:left;margin:1px;}
#aqua{background:aqua;}
#yellow{background:yellow;}
#bisque{background:bisque;}
#aquamarine{background:aquamarine;}
#target{float:left;padding:20px;height:200px;width:250px;border:#F0F0F0 1px solid;}
</style>
This script contains very few lines to implement jQuery color picker. We have a pointer to track color on mouse move. On the click event of the color palette, we select the color code and save it to the pointer object.
This color code will be applied as the target DIV’s background on its click event.
<script type="text/javascript">
var demoContent = document.getElementById("demo-content");
demoContent.addEventListener('mousemove',function(event) {
$("#pointer").css({'top':event.pageY+'px','left':event.pageX+'px'});
});
function applyColor(){
$("#target").css('background-color',$("#pointer").css('background-color'));
}
function pickColor(id){
$("#pointer").css('background-color',id);
}
</script>