Bootstrap Colorpicker is a GUI widget which can be used to show a color pallet to pick colors. This is a jQuery based Bootstrap plugin.
Using this plugin, an HTML element will be bound to show the color picker. We can easily implement color picker in our application using this Bootstrap library. It makes our job easy to get colors from the color panel instead of punching down color codes.
In this example, I bind an HTML button element with the Bootstrap color picker. I invoke the color picker with the reference of the button element.
On clicking this button handle, the color panel will be shown to the user to select colors. I used the Bootstrap Colorpicker to change the background color of a DIV element dynamically. In a previous tutorial, I have created an example for changing DIV background dynamically on page scroll.
This screenshot shows the colorpicker and the changed background of the target DIV element.
This HTML code contains a DIV element and a button. The button element will be bound with the Bootstrap Colorpicker. This binding will be done on the click event of this button to show the color picker.
On selecting a color, then it will be applied as the background color of the DIV element.
Download Bootstrap Colorpicker library and include the required JavaScript and CSS dependencies in your HTML.
<link rel="stylesheet" href="bootstrap-colorpicker.min.css">
<script src="jquery-3.2.1.min.js"></script>
<script src="bootstrap-colorpicker.js"></script>
<div class="row">
<div id="div-bg"></div>
<button id="btn-color-picker" class="btn btn-primary btn-md">
<img src="ic_color_lens.png" />
</button>
</div>
and the styles are,
<style>
#div-bg {
height: 200px;
width: 200px;
border: 1px solid black;
display: inline-block;
box-sizing: border-box;
}
#btn-color-picker {
background: none;
border: #000 1px solid;
padding: 2px;
cursor: pointer;
}
</style>
In this simple script, the Colorpicker library function is initialized with respect to the button element’s id selector. The button element shows the color picker icon.
On clicking this button icon, the color panel will be shown to the user. When the user selecting the color, then the DIV background is changed using jQuery css() function. The color changing process will be done on the changecolor event of the colorpicker widget element.
<script type="text/javascript"
$('#btn-color-picker').colorpicker();
$('#btn-color-picker').colorpicker().on(
'changeColor',
function() {
$('#div-bg').css('background-color',
$(this).colorpicker('getValue', '#ffffff'));
});
</script>