Search code examples
javascriptcanvasjscolor

Dynamically Update jscolor palette after setting default


I am wanting to use jscolor to create a color picker that also saves recent color choices to the palette. So I need the palette to be updated dynamically upon changing... I feel like this would be a common ask, but I am not seeing anything to do this... Any help would be appreciated!

jscolor docs page here: https://jscolor.com/docs/

let customColors =  [
        '#2C2B2B', '#FFEE92', '#17C3B2', '#71A5DE', '#C27EC2', '#FE6D73',
    ];

jscolor.presets.default = {
    position: 'right',
    palette: customColors,
    //paletteCols: 12,
    hideOnPaletteClick: true,
};
const colorPicker = document.getElementById('color-picker');
colorPicker.addEventListener('input', () => {
        customColors.push(colorPicker.value);
        
        //somehow update the palette here........
});

I tried messing with presets and using jscolor.install(); but was unable to get the palette to update.


Solution

  • According to its documentation, you need to update the option from the jscolor's instance.

    let customColors =  [
        '#2C2B2B', '#FFEE92', '#17C3B2', '#71A5DE', '#C27EC2', '#FE6D73',
    ];
    
    jscolor.presets.default = {
        position: 'right',
        palette: customColors,
        //paletteCols: 12,
        hideOnPaletteClick: true,
    };
    const colorPicker = document.getElementById('color-picker');
    colorPicker.addEventListener('input', () => {
        customColors.push(colorPicker.value);
    
        // update palette option from instance
        colorPicker.jscolor.option('palette', customColors);
    });