Claes Gustavsson
Claes Gustavsson

Reputation: 5687

Set gradient backgroundcolor from colorpicker with jquery?

I want to beable to select 2 colors and display a div with a gradient background!

I have 2 colorpickers done with "jscolor.com" where I can select colors and the color I choose gets displayed in an input field.

Top color<br />
<input type="text" name="color1" class="colors" size="7" value="#444444"/>
<br><br>
Bottom color<br />
<input type="text" name="color2" class="colors" size="7" value="#17181a"/>

and then the div where I would like to display a gradient background.

<div id="gradient"></div>

How can I set the background color based on the input fields? And suggestions appriciated, thanks.

Upvotes: 2

Views: 3469

Answers (1)

kubetz
kubetz

Reputation: 8566

Steps:

  • give inputs unique IDs so you can retrieve them easily.
  • use jQuery's .css() to set background-image: linear-gradient... and don't forget to include all vendor prefixes.
  • refresh linear-gradient when input changes and when page is loaded

Example:

$(function() {
  // when inputs change, update the gradient
  $(".color").change(refreshGradient);
  // draw the gradient when page is loaded
  refreshGradient();
});

function refreshGradient() {
  var gradientBody = 'linear-gradient(top, ' + $("#color1").val() + ', ' + $("#color2").val() + ')';

  // we need to use vendor prefixes
  $.each(['', '-o-', '-moz-', '-webkit-', '-ms-'], function() {
    $("#gradient").css({ 'background-image': this + gradientBody });
  });
}

HERE is the code.

Update: (see comments)

To integrate the with jQuery minicolors .change() handler must be registered differently:

$(".color").miniColors({
  change: refreshGradient
});

HERE is the example using jQuery miniColors plugin.

Upvotes: 5

Related Questions