Your Friend Ken
Your Friend Ken

Reputation: 8872

HTML Color selector input

I was working on an HTML form today and needed to create a color selector when I discovered (on accident) that input type 'color' actually creates a color selector in chrome (as well as firefox http://caniuse.com/#feat=input-color).

enter image description here

<input type="color" value="#333" />

Are there any examples of using the color input type with gracefully fail over to other selectors?

Also it would be nice to show the hex value generated. In chrome it just shows a button box with the background of the selected color.

Is there a way to style an HTML color input to show the selected color's hex value?

Upvotes: 5

Views: 4440

Answers (2)

Your Friend Ken
Your Friend Ken

Reputation: 8872

Here is what I ended up using:

$("input.color").each(function() {
  var that = this;
  $(this).parent().prepend($("<i class='fa fa-paint-brush color-icon'></i>").click(function() {
    that.type = (that.type == "color") ? "text" : "color";
  }));
}).change(function() {
  $(this).attr("data-value", this.value);
  this.type = "text";
});
label {
  font-family: sans-serif;
  width: 300px;
  display: block;
  position: relative;
}
input {
  padding: 5px 15px;
  font-size: 16px;
  width: 100%;
  box-sizing: border-box;
}
input[type=color] {
  padding: 0;
  border: 0;
  height: 40px;
}
input[type=color]:after {
  content: attr(data-value);
  position: absolute;
  bottom: 10px;
  text-align: center;
  color: #fffff5;
  display: block;
  width: 100%;
}
.color-icon {
  position: absolute;
  bottom: 10px;
  right: 10px;
  color: #666;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<label>
  Color:
  <br />
  <input class="color" placeholder="#XXXXXX" data-value="#xxxxxx" />
</label>

Upvotes: 2

arcyqwerty
arcyqwerty

Reputation: 10675

Are there any examples of using the color input type with gracefully fail over to other selectors?

You could find ways to gracefully fallback to another color picker if color input is not available. For example, https://github.com/bgrins/spectrum. (Try searching for "input color polyfill" for other options).

Is there a way to style an HTML color input to show the selected color's hex value?

For my Chrome (45.0.2454.93), it does show the hex value in the color selector while selecting. If you want to show it after selecting, the value of the input appears to be in hex.

document.querySelector('input[type=color]').value

If you want to display that to a user, you could populate another element with that value when onchange is fired for the input element.

Upvotes: 1

Related Questions