Question

Within JQuery we are able to trigger 'click' on any given element with:

$(selector).trigger('click');

Though i have difficulties doing so when the element is a HTML 5 color picker and the 'display' property is set to 'none' by CSS.

Normally we can do this if the input type is 'file' or ...

So is there anyway to get this done with JQuery or plain javascript?

HTML elements

input type="color" id="fontSel" style="display: none;"
div id="fontWrap"

JQuery

$("#fontWrap").click(function(){
     $("#fontSel").trigger("click");
});



ANSWER

Change the style to:

input type="color" id="fontSel" style="position:absolute; left:-9999px; top:-9999px;"
Était-ce utile?

La solution

This need user interaction, meaning you cannot trigger it without user clicking somewhere in document:

DEMO

$("#fontWrap").click(function () {
    $("#fontSel")[0].click();
});

Autres conseils

Alternative of the accepted answer is to use label tag and let the browser do the work for you.

For example:

<input type="color" id="my-color" style="opacity: 0; visibility: hidden; position: absolute;">

<label for="my-color">Click here</label>

The accepted answer works great, except it doesn't work in MS Edge (I personally don't like it much, but it's still 6% market share as of 2017, meaning every ~15th visitor of your website has it)

So here's a good old "hover-hack" trick that works in all browsers:

<input type="color" style='opacity:0;width:100px;position:absolute;'/>
<button>clickme</button>

And then bind onchange to the color element to get the selected value. Experiment with widths/heights for your layout.

https://jsfiddle.net/Lnzm0sry/2/

PS. I know it's "hacky", but I don't have a better idea.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top