Filippo oretti
Filippo oretti

Reputation: 49817

JavaScript / jQuery graduating desaturate HEX colors

Starting from (say) #ff0011 I would like to graduating scale the background-color for each element div I have in page.

The result should be something like:

    <div class="div-1"></div> // background-color:#ff0011;
    <div class="div-2"></div> // background-color:#ff0011 -0.2% saturation;
    <div class="div-3"></div> // background-color:#ff0011 -0.3% saturation;
    <div class="div-4"></div> // background-color:#ff0011 -0.4% saturation;
    <div class="div-5"></div> // background-color:#ff0011 -0.5% saturation;

Hope the example is clear, I really don't know where to start on doing this so any link tutorials will be really appreciated.

EDIT: i'm talking about graduating DESATURATE colors

Upvotes: 0

Views: 791

Answers (4)

Filippo oretti
Filippo oretti

Reputation: 49817

Ok guys, i found out how to do that , thanks to everyone of you, but this is the code i needed:

var i = 50;
    $.each($('div'),function(){
    $(this).css({'background-color':'hsl(145,37%,'+i+'%)'});
    i++
    });

thanks to @KKetch who gives me the css3 hsl() example!

Upvotes: 1

Sushanth --
Sushanth --

Reputation: 55740

You can use jQuery or Javascript to get that working ..

Using Javascript

var elems = document.getElementsByTagName('div');

for(var i =0;i< elems.length ; i++){
      var op = 1 - (i/10);
      var fil = 100 - (i * 10);
      elems[i].style.opacity = op;
     elems[i].style.filter = "alpha(opacity=" + fil + ")";
}

HTML & CSS

<div class="div"></div>
<div class="div"></div> 
<div class="div"></div> 
<div class="div"></div> 
<div class="div"></div> ​

.div
{
    background-color: #ff0011;
    width:100px;
    height:50px;
    border : 1px solid green;
}​

Check Fiddle

Upvotes: 0

kketch
kketch

Reputation: 693

Is using CSS3 hsl an option ? You would have easy (and REAL) control to calculate lighter or darker colors. https://developer.mozilla.org/en-US/docs/CSS/color_value#hsl()

It doesn't work on IE8 and below, but is widely supported across modern browsers.

Upvotes: 2

Sidharth Mudgal
Sidharth Mudgal

Reputation: 4264

HTML:

<div class="div-1 shaded"></div> // background-color:#ff0011;
<div class="div-2 shaded"></div> // background-color:#ff0011 0.2% lighter;
<div class="div-3 shaded"></div> // background-color:#ff0011 0.3% lighter;
<div class="div-4 shaded"></div> // background-color:#ff0011 0.4% lighter;
<div class="div-5 shaded"></div> // background-color:#ff0011 0.5% lighter;

JS:

$('.shaded').each(function(i){
    $(this).css('opacity', (1 - i/10));
});

Here's a fiddle demonstrating this made by Sushanth

Upvotes: 2

Related Questions