Farbtastic color picker to change the background color of text field input? I have taken this JS from the field_example module. I am attaching it to a form textfield element so that when a user brings focus to it the Farbtastic color picker widget pops up and allows the user to populate the field with the chosen hexadecimal color code. It works as expected. I was also expecting the background of the field to dynamically match the chosen color like this. However, it does not. In the linked example the text also turns black/white depending on the chosen color. This feature is also present in the color module.

I've tried adding to the code below, but nothing I try works. How can I adapt the JS below to achieve this? Thanks.

JS

/**
 * @file
 * Farbtastic color picker.
 */

/**
 * Show farbtastic colorpicker widget.
 */
(function ($) {
  Drupal.behaviors.my_color_picker = {
    attach: function(context) {

      $(".edit-my-color-picker").live("focus", function(event) {
        var edit_field = this;
        var picker = $(this).closest('div').parent().find(".my-color-picker");

        // Hide all color pickers except this one.
        $(".my-color-picker").hide();
        $(picker).show();
        $.farbtastic(picker, function(color) {
          edit_field.value = color;
        }).setColor(edit_field.value);
      });

    }
  }
})(jQuery);


Form element

'color' =&gt; array(
  '#type' =&gt; 'textfield',
  '#title' =&gt; t('Color'),
  '#size' =&gt; 8,
  '#suffix' =&gt; '&lt;div class="my-color-picker"&gt;&lt;/div&gt;',
  '#attributes' =&gt; array(
    'class' =&gt; array(
      'edit-my-color-picker',
    ),
  ),
  '#attached' =&gt; array(
    'library' =&gt; array(
      array(
        'system',
        'farbtastic',
      ),
    ),
    'js' =&gt; array(
      drupal_get_path('module', 'my_module ') . '/color-picker.js',
    ),
  ),
),
Something like this?

/**
 * Show farbtastic colorpicker widget.
 */
(function ($) {
  Drupal.behaviors.my_color_picker = {
    attach: function(context) {

      $(".edit-my-color-picker", context).on("focus", function(event) {
        var edit_field = $(this);
        var picker = edit_field.closest('div').parent().find(".my-color-picker");

        // Hide all color pickers except this one.
        $(".my-color-picker").hide();
        $(picker).show();
        $.farbtastic(picker, function(color) {
          edit_field.val(color);
          // background color, may need to add # to color.
          $(edit_field).css("background-color", color);
        }).setColor(edit_field.value);
      });

    }
  }
})(jQuery);


Notice I added 'context' to the original selector and changed 'live' to 'on'. Live function is deprecated as of jquery 1.7.
I also changed it so the edit_field variable stores the jquery object.

Drupal does already have a couple of color fields, on of which is HERE