codek
codek

Reputation: 343

Background color change transition with jquery

This is what i´m trying to achieve:

enter image description here

The user will have the option to add more years (a new circle with text and the next color in the gradient).

So what i´m doing is building a div that by repeating itself it can construct the above image.

This is the markup:

     <a href="javascript:void(0)" class="timeline_box">
        <span class="timeline_dot"></span>
        <span class="timeline_year">2003</span>
    </a>

This is the CSS:

    a.timeline_box{
        background: url('../images/timeline_bg.png') no-repeat 15px -2px;
        display: block;
        width: 56px;
        height: 20px;
        float: left;
    }
    span.timeline_dot{
        display: block;
        height: 14px;
        width: 14px;
        background-color: #ff845a;
        -moz-border-radius: 5px;
        -webkit-border-radius: 10px;
        -khtml-border-radius: 5px;
        border-radius: 10px;
    }
    span.timeline_year{
        color: #b6b6b6;
        font-size: 10px;
        font-style: italic;
        font-family: Georgia, Times, "Times New Roman", serif;
        vertical-align: top;
    }

This is what I get:

enter image description here

and if I repeat the timeline_box it start to construct well:

enter image description here

The client now can change the year but the problem is that the background color of the circle will stay always the same, I want to find a way to change it with jquery that with every new year the background of the circle get´s the next color on the gradient or something like that.

Any ideas?

Upvotes: 4

Views: 815

Answers (1)

Paulo R.
Paulo R.

Reputation: 15609

Never tried something of this kind - changing colors while following the color gradient or whatever. Thought it would be trickier than it is. The hsl color format makes it pretty easy to do. To "follow the gradient" you just need to keep incrementing the h in hsl - the logic is simple.

Here's the javascript:

var $box = $('.timeline_box'),
    h_val = 0;

function addBox () {
  var $new_box = $box.clone();
  h_val += 17; //change this value to change the amount of color change

  $new_box
    .find('.timeline_dot')
    .css('background', 'hsl('+ h_val +', 100%, 68%)') //change the "s" and "l" values to your liking
    .end()
    .appendTo('body'); 
}

$('#el').on('whatever', addBox);

There's not even the need to reset the h to 0 at some whatever point. The h can keep going on and on, and it'll just keep cycling the gradient.

Here's a jsbin: http://jsbin.com/oqifoq/1/edit

Upvotes: 3

Related Questions