Search code examples
javascripthtmlonchangejscolor

jscolor picker, how to use onchange event for a button?


I am using jscolor v2.0.4 from East Desire. All works fine but the onchange event does not work if I use a button.

In the onchange event sample on the webpage is an input field used. but I use a button element and here is only the onFineChange event possible. Why?

Here is my code:

<button style="border:2px solid black; width:80px; height:30px" class="jscolor {valueElement:'chosen-value', closable:true,closeText:'Close me!', onFineChange:'updateColor(this)'}">Pick color</button>
R, G, B = <span id="rgb"></span>

<script>
function updateColor(picker) {
    document.getElementById('rgb').innerHTML = Math.round(picker.rgb[0]) + ', ' + Math.round(picker.rgb[1]) + ', ' + Math.round(picker.rgb[2]);
}
</script>

If I change the onFineChange to onchange then it does not work. What can I do?


Solution

  • You have to pay attention to the example markup. onchange was part of the input element, not part of jscolor implementation.

    <input class="jscolor" onchange="update(this.jscolor)" value="cc66ff">
    
    <input class="jscolor {onFineChange:'update(this)'}" value="cc66ff">
    

    If you see the markup then you'll understand that onchange is not jscolor's implementation.

    If you check the source code of jscolor you'll also find that. onChange is meant to fire only on inpyt type elements, not on buttons

    dispatchChange : function (thisObj) {
            if (thisObj.valueElement) {
                if (jsc.isElementType(thisObj.valueElement, 'input')) {
                    jsc.fireEvent(thisObj.valueElement, 'change');
                }
            }
        },
    

    ref: https://github.com/EastDesire/jscolor/blob/master/jscolor.js#L671

    So if you want onchange event, then you have to change your button to input type

    or you can create input type="button" and then listen to the event onchange, because the plugin only cares about input not the type

    <input class="jscolor" id="btnPicker" type="button">
    <script>
    
    document.getElementById('btnPicker').addEventListener('change', function(e){
        updateColor(this.jscolor)
    })
    function updateColor(picker) {
        document.getElementById('rgb').innerHTML = Math.round(picker.rgb[0]) + ', ' + Math.round(picker.rgb[1]) + ', ' + Math.round(picker.rgb[2]);
    }
    </script>