• Post category:JavaScript
  • Reading time:5 mins read

Today we’ll show you how to add jQuery color picker using bootstrap 3. In this article, we will give you an example to create a color picker components using bootstrap version 3.

Color picker using Bootstrap 3

  1. Include JS and CSS
  2. Create HTML content
  3. Initialize color picker
  4. Output

1. Include JS and CSS

Let’s create a HTML file and add the following JS library and CSS links to implement bootstrap 3.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-colorpicker/2.5.3/css/bootstrap-colorpicker.css" rel="stylesheet">

<script src="https://code.jquery.com/jquery-2.2.2.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-colorpicker/2.5.3/js/bootstrap-colorpicker.js"></script>

2. Create HTML content

In the next step, create a HTML content and bind the color picker with it. Therefore we will create a div element that contains input and span elements. On click of this element, we will open a color picker component to pick a color.

<div id="cp-component" class="input-group">
  <input type="text" value="#269faf" class="form-control">
  <span class="input-group-addon"><i></i></span>
</div>

In the above code, we have passed the default color code as a value in the input field.

3. Initialize color picker

At last, we have to initialize the color picker component using jQuery. Add the following code at the bottom of the page.

<script type="text/javascript">
  $(function () {
    $('#cp-component').colorpicker();
  });
</script>

4. Output

Let’s combine all code together in an HTML file and run the file in the browser.

index.html

<!DOCTYPE html>
<html>

<head>
  <title>Colorpicker using Bootstrap 3 - Code Premix</title>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-colorpicker/2.5.3/css/bootstrap-colorpicker.css"
    rel="stylesheet">

  <script src="https://code.jquery.com/jquery-2.2.2.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-colorpicker/2.5.3/js/bootstrap-colorpicker.js"></script>
</head>

<body>
  <div style="width: 400px; margin: 20px auto; text-align: center;">
    <h4>Colorpicker using Bootstrap 3 - <a href="https://codepremix.com">Code Premix</a></h4>
    <div id="cp-component" class="input-group">
      <input type="text" value="#269faf" class="form-control" />
      <span class="input-group-addon"><i></i></span>
    </div>
  </div>

  <script type="text/javascript">
    $(function () {
      $('#cp-component').colorpicker();
    });
  </script>
</body>

</html>

That’s it for today.
Thank you for reading. Happy Coding..!! 🙂

Source Code

GitHub Repository

Leave a Reply