Preview hex color in HTML with Prototype

2007-04-02

In an ongoing work for some client, I had to make a small form to build front-end skins for the website.

3 colors were part of the skin and the client wanted to preview the color as he was typing the hex value.

I ended with a few javascript lines of code based on Prototype (great JS Framework).

Here is the code :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
  <meta http-equiv="Content-type" content="text/html; charset=utf-8">
  <title>Page Title</title>
  <style type="text/css" media="screen">
      .preview_color {
          width: 50px;
          height: 24px;
          background-color: #fff;
          border: 1px solid #ccc;
          display: block;
          float: left;
}
  </style>
  <script src='https://ajax.googleapis.com/ajax/libs/prototype/1.7.3.0/prototype.js' type='text/javascript' language='Javascript'
charset='iso-8859-1'></script>
  <script type="text/javascript" charset="utf-8">
      function changeColor(el, value) {
          var color = value
          $('preview_' + el.name).style.backgroundColor = "#" + color
      }
      Event.observe(window, 'load', function() {
          new Form.Element.Observer('color_1', 0.2, changeColor)
          new Form.Element.Observer('color_2', 0.2, changeColor)
          new Form.Element.Observer('color_3', 0.2, changeColor)
});
  </script>
</head>
<body>
  <form>
    <table border="0" cellspacing="5" cellpadding="5">
      <tr>
        <th>
          <label for="color_1">Couleur 1 : </label>
        </th>
        <td>
          #<input type="text" name="color_1" id="color_1" maxlength="6" size="6" />
        </td>
        <td>
          <div id="preview_color_1" class="preview_color" ></div>
        </td>
      </tr>
      <tr>
        <th>
          <label for="color_2">Couleur 2 : </label>
        </th>
        <td>
          #<input type="text" name="color_2" id="color_2" maxlength="6" size="6" />
        </td>
        <td>
          <div id="preview_color_2" class="preview_color" ></div>
        </td>
      </tr>
      <tr>
        <th>
          <label for="color_3">Couleur 3 : </label>
        </th>
        <td>
          #<input type="text" name="color_3" id="color_3" maxlength="6" size="6" />
        </td>
        <td>
          <div id="preview_color_3" class="preview_color" ></div>
        </td>
      </tr>
    </table>
  </form>
</body>
</html>