Search code examples
jquerycolor-picker

Accessing the trigger of the colorpicker


I'm using the following jquery color picker on my project - www.eyecon.ro/colorpicker. I'm using multiple colorpickers on the same page, calling the script on a class ( I have 7 inputs on which the color picker is applied and none of them are related ). The problem I'm having is that I can't access the trigger as there is no relation between the colorpickers and their triggers.
Does anyone know how to do this? Basically I'm trying to use this function

(...)onChange: function (hsb, hex, rgb) {
     $(this).css('backgroundColor', '#' + hex);
}

Where $(this) should be the parent, but obviously it's not.


Solution

  • You need to bind the function to a context , so before calling the function , declare that

    var that = this // or whatever this(the context) is 
    

    then call that in the callback instead of this.

    ...)onChange: function (hsb, hex, rgb) {
         $(that).css('backgroundColor', '#' + hex);
    }
    

    EDIT : here is the javascript code i would write.

    $(document).ready(function() {
        $('.colorpickerHolder').each(function(o) {
            var _this = this;
            $(this).ColorPicker({
                onChange: function(hsb, hex, rgb) {
    
                    _this.style.background = '#' + hex;
                    // the input which is trigger the colorpicker is supposed to be $(THIS);
                }
            })
        })
    });​
    

    http://jsfiddle.net/camus/PQDf8/4/