简体   繁体   中英

manual click event only triggers on second click

I build a small color-picker module. But it only opens up (and then works) when pickColor is called a second time. I also tried to wrap the _openColorPicker into a setTimeout but that didn't work either. In fact, the color-picker didn't show up at all when I did that.

What I found interesting is that the binding to the change event works, so the $ selector must have found the element already.

So I have two questions:

1) why is the picker only showing after the second call to _openColorPicker ?

2) why didn't the picker open at all when I wrapper the _openColorPicker call in a setTimeout ?

Edit: The _openColorPicker functions gets executed after the user has right-clicked into the document and then clicked on context-menu which is now showing.

Complete Code:

const ColorUtils = {

    _initialized: false,

    _openColorPicker: function () {
        $('#color-picker').click();
    },

    pickColor: function (onChangeCallback, context) {
        if (!this._initialized) {
            $('<input/>').attr({
                type: 'color',
                id: 'color-picker',
                display: 'hidden',
                value: '#ffffff'
            }).appendTo('#centralRow');
            this._initialized = true;

            $('#color-picker').on('change', onChangeCallback.bind(context));
        }
        this._openColorPicker();

        // version with timeOut
        const scope = this;
        setTimeout(function () {
             scope._openColorPicker();
        }, 1000);
    }
};

export default ColorUtils;

Above code is used like ColorUtils.pickColor(onColorPicked, this);

Check out this post . Looks like you can't trigger a click on an invisible color picker. That answer suggests giving the element an absolute position and placing it off screen, like so:

position:absolute;
left:-9999px;
top:-9999px;

I tried to replicate your case (for what I understood) : JSFIddle

I made some changes. I moved the $('<input/>') in a property of the object ColorUtils and appended it to the DOM with absolute position and outside the screen.

(And also commented display:'hidden' because it's either display:none or visibility:hidden and as a CSS property, not Html attribute)

On right clic on the document I instantiate the picker (and register the callback + context) then add a button to the DOM to trigger the picker again.

Does it fulfill your requirements ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM