Search code examples
javascriptjqueryhtmlcssspectrumjs

How to set options for spectrum js in case of fallback from color type input?


I am using the Spectrum JS as a fallback for browsers that does not support <input type="color>. To do so, just include the Spectrum JS library and everything is done automatically.

http://bgrins.github.io/spectrum/#modes-input

A working example: http://jsfiddle.net/ctkY3/5542/

You should see the default color input box except when using IE. (Yes, even IE11 doesn't support color input. MS only support color input in Edge)

The problem is that once using the $(element).spectrum() function, it will show the spectrum color picker for all browser, while I just want to use it as a fallback. So, how can I add options to the fallback color picker?


Solution

  • Before calling spectrum on your jQuery object, you should check if the dom is ready and also if the browser supports color input.

    Just as this answer shows, when an input is not supported, it will default to text.

    So, assuming you have an input with id picker, you can try the following:

    $(document).ready(function() {
        var i, colorInputSupported;
        i = document.createElement("input");
        i.setAttribute("type", "color");
        colorInputSupported = i.type !== "text";
    
        if(!colorInputSupported){
          $("#picker").spectrum({
            // Here you put the options
            color: "#f00"
          });
        }
    });
    

    Here is a working example of this code.

    As an alternative, spectrum supports setting the options of the picker in the HTML element itself, via data attributes. For instance:

    <input type='color' id="picker" data-color="#f00"/>
    

    Will generate a color picker starting in red color, which will be displayed only in browsers that do not support the default color picker.

    Here is a working example. For a complete list of options, you can check them in spectrums docs