Search code examples
javascriptjquerycssspectrum

onchange doesn't fire when modified by javascript


I am using spectrum (https://github.com/bgrins/spectrum), a jQuery plugin for color palletes. My goal is that the color is being directly applied on the background, while the user is browsing the different colors.

What I have so far is this:

//*****Part of a 3rd party file, which I cannot modify****
$("#picker1").spectrum({
    allowEmpty:true,
    color: "#ECC",
    showInput: true,
    preferredFormat: "hex",
}); 
//***********************************


$("#picker1").on("change keyup paste", function(){
    newcolor=$("#picker1").val();
    $(".menu-itempreview").css("background-color", newcolor);     
});



<ul id="menu-primary-menupreview" class="someclass">
    <li class="menu-itempreview">Home</li>
    <li class="menu-itempreview">Sample Page</li>
    <li class="menu-itempreview">Uncategorized</li>
</ul>


<input type='input' id="picker1" />

Fiddle me here: http://jsfiddle.net/h4Lc5b6a/

The problem is, that the color only updates when the user hits the submit button. How would I be able to make it, so that the background updates on the fly, while the user is browsing the different colors?

It seems the problems lies with the onchange, which doesn't fire when the input field is being modified by javascript.


Solution

  • You can use the move callback (http://bgrins.github.io/spectrum/#events-move).
    Add to your spectrum initialization:

    $("#picker1").spectrum({
        //...,
        move: function(color) {
            $(".menu-itempreview").css("background-color",  color.toHexString());
        }
    }); 
    

    Also you can use this after the spectrum initialization:

    // Alternatively, they can be added as an event listener:
    $("#picker").on('move.spectrum', function(e, tinycolor) { });
    $("#picker").on('show.spectrum', function(e, tinycolor) { });
    $("#picker").on('hide.spectrum', function(e, tinycolor) { });
    $("#picker").on('beforeShow.spectrum', function(e, tinycolor) { });