3

I am trying to run some custom jquery function every time the colorpicker's color change. The colorpicker is include as part of the WP core. I have been looking at the JS code, but I can't figure out what's the trigger that updates the color.

I have tried listening for several classes, and also listening for changes on the text input (the one that holds the color hex value), but no luck.

Has anyone done this before?

0
6

I hate answering my own question, but hopefully this can help someone else with similar issues:

Wordpress uses Iris color picker. http://automattic.github.io/Iris/#

Wordpress also creates a jquery widget with default settings for Iris. The file can be found under wp-admin/js/color-picker.js

At first I was trying to pass values directly to iris(), which works, but that overrides the wordpress widget.

Once I found out about the widget, I wrote the following:

$(".wp-color-picker").wpColorPicker(
  'option',
  'change',
  function(event, ui) {
    //do something on color change here
  }
);

The wpColirPicker accepts a custom function for the change event. So it runs first the default actions and then it allows you to add your own.

1

As gdaniel was saying in his answer, WordPress uses Iris color picker. You can pass your callbacks to wpColorPicker plugin using change and clear options. Please note that change-callback will handle all the changes except for cleaning of the field via "Clear" button. So use clear-callback for that purposes.

jQuery('.wp-color-picker').wpColorPicker({
    /**
     * @param {Event} event - standard jQuery event, produced by whichever
     * control was changed.
     * @param {Object} ui - standard jQuery UI object, with a color member
     * containing a Color.js object.
     */
    change: function (event, ui) {
        var element = event.target;
        var color = ui.color.toString();

        // Add your code here
    },

    /**
     * @param {Event} event - standard jQuery event, produced by "Clear"
     * button.
     */
    clear: function (event) {
        var element = jQuery(event.target).siblings('.wp-color-picker')[0];
        var color = '';

        if (element) {
            // Add your code here
        }
    }
});

Please also note that if you use element.value in your change-callback then you'll get the old value instead of new one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.