Search code examples
javascriptjqueryspectrumjs

Update new color in Spectrum JS Colorpicker Palette


I'm useing spectrum jQuery colorpicker and changing the background-color working properly but there's just one problem. after refreshing the page,the color of the chooser button gets black instead of selected color (for example, red) background color of the page changed without any problem and everything worked properly except that. Look at this(click to see images):

Selected Color -> after refreshing the page

This is my code:

HTML:

<input id="colorpicker" style="display: none;">

JS:

var currColor = $.cookie('body_color') || 'rgba(0, 0, 0, 0.5)';
 $('body').css('background-color', currColor);
 $("#colorpicker").spectrum({
    preferredFormat: 'rgb',
     showInput: true,
     showAlpha: true,
     color: currColor.substring(1),
     move: function(color) {
         $('body').css('background-color', color.toRgbString());
         $.cookie('body_color', color.toRgbString(), {
             expires: 365
         });
     }
 });

how can I fix this?

If I change color.toRgbString() to color.toHexString() this issue get fixed but another issue occurs (after that I cant use rgba colors for page's background and transparency not work):

var currColor = $.cookie('body_color') || 'rgba(0, 0, 0, 0.5)';
     $('body').css('background-color', currColor);
     $("#colorpicker").spectrum({
        preferredFormat: 'rgb',
         showInput: true,
         showAlpha: true,
         color: currColor.substring(1),
         move: function(color) {
             $('body').css('background-color', color.toHexString());
             $.cookie('body_color', color.toHexString(), {
                 expires: 365
             });
         }
     });

Solution

  • I have an idea, but you should edit the spectrum.js file. This function function inputToRGB(color) forced rgba color of color chooser buttons to set to the rgb(0, 0, 0) (when you choose rgba color, after refreshing the page, the colorpicker button's color forced to set to that but there is no problem with hex).

    to fix this:

    Find this code in spectrum.js:

    function inputToRGB(color) {
    
        var rgb = { r: 0, g: 0, b: 0 };
        var a = 1;
    

    then change above codes to:

        function inputToRGB(color) {
    
       var colorString = color.toString(),
           colorsOnly = colorString.substring(colorString.indexOf('(') + 1, colorString.lastIndexOf(')')).split(/,\s*/),
           red = colorsOnly[0],
           green = colorsOnly[1],
           blue = colorsOnly[2],
           opacity = colorsOnly[3];
    
        var rgb = { r: red, g: green, b: blue };
        var a = opacity;
    

    Use above regex to get color values from browser cookie then extract color values of 4 sections of rgba color codes, then use those in 'rgb' & 'a' variables! you can use both of color.toString() or color.toRgbString().