user6342181
user6342181

Reputation:

How to trigger color dialog from js code

I have

<input type="color" id="colorDialogID">
<div id="textToColorID">Text to color</div>
<input type="button" id="setColorButtonID">  

and I want to by clicking on button to display color dialog. And when I select particular color and press on 'ok', some text to get the selected color.

I need js code for this. I am googling almost one hour now to find a way how to display code picker window from code and no success. I get only kind of plugins. I can not understand why everything has to be so complicated with javascript.

Upvotes: 2

Views: 1929

Answers (2)

user8313246
user8313246

Reputation:

OK, for future reference it is always good to provide a snippet of your code - or even better a JSFiddle link but this is what I've got now.

document.getElementById("setColorButtonID").addEventListener("click", function() {
  document.getElementById("colorDialogID").focus();
  document.getElementById("colorDialogID").value = "#FFCC00"; //Set the default color  NOTE: Remove the line to get the default of #000000
  document.getElementById("colorDialogID").click();
});

function getColor() {
  var color = document.getElementById("colorDialogID").value;
  document.getElementById("textToColorID").style.color = color;
}
#colorDialogID {
  position: absolute;
  visibility: hidden;
}
<input type="color" id="colorDialogID" onchange="getColor(this)">
<div id="textToColorID">Text to color</div>
<input type="button" id="setColorButtonID" value="Edit Color">

I can add some comments to the code to explain it line by line if you wish - but this should work.

Hope it helps :)

Upvotes: 3

Zulfe
Zulfe

Reputation: 881

Take a look at jscolor. It's dead simple and the functionality that you're looking for can be easily reached.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jscolor/2.0.4/jscolor.min.js"></script>

Color: <input class="jscolor" value="ab2567">

Upvotes: 0

Related Questions