onchange doesn't fire when modified by javascript

不打扰是莪最后的温柔 提交于 2019-12-25 02:53:34

问题


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.


回答1:


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) { });


来源:https://stackoverflow.com/questions/29463275/onchange-doesnt-fire-when-modified-by-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!