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' => array(
'#type' => 'textfield',
'#title' => t('Color'),
'#size' => 8,
'#suffix' => '<div class="my-color-picker"></div>',
'#attributes' => array(
'class' => array(
'edit-my-color-picker',
),
),
'#attached' => array(
'library' => array(
array(
'system',
'farbtastic',
),
),
'js' => array(
drupal_get_path('module', 'my_module ') . '/color-picker.js',
),
),
),