Indigo
Indigo

Reputation: 787

How to have a timed-gradient effect?

I want a circle border to have different color displayed every 2 seconds. I would prefer if it was a gradient, so the colors do not pop out.

JavaScript

setTimeout(function() {
    $(".circle").css("border", "10px solid blue")
}, 2000);

CSS

.circle{
    background-color: #000;
    border-radius: 500px;
    border: 10px solid #FFF;
    color:#fff;
    font-size:20px;
    height: 500px;
    line-height:100px;
    margin: 0px auto;
    text-align:center;
    width: 500px;
}

Upvotes: 2

Views: 669

Answers (3)

Brett DeWoody
Brett DeWoody

Reputation: 62773

If you want a CSS-only solution:

You can use CSS animations to change the border color over time.

HTML

<div></div>

CSS

div {
    width:100px;
    height:100px;
    border-radius:1000px;
    border-width:10px;
    border-style:solid;
    -webkit-animation: changeColor 10s; 
    animation: changeColor 10s;
    -webkit-animation-iteration-count: infinite;
    animation-iteration-count: infinite;
    -webkit-animation-direction: alternate;
    animation-direction: alternate;
}

@-webkit-keyframes changeColor {
    0%   {border-color: red;}
    33%  {border-color: yellow;}
    66%  {border-color: blue;}
    100% {border-color: green;}
}

@keyframes changeColor {
    0%   {border-color: red;}
    33%  {border-color: yellow;}
    66%  {border-color: blue;}
    100% {border-color: green;}
}

And here's the final product.

Upvotes: 1

royhowie
royhowie

Reputation: 11171

The easiest way would be to use a setInterval:

var i = setInterval(function () {
    var color = '#' + (Math.random()*0xFFFFFF|0).toString(16);
    // this produces a random hex code
    // taken from http://www.paulirish.com/2009/random-hex-color-code-snippets/
    $(".circle").css("border", "10px solid " + color);
}, 2000);

To color them each differently:

var i = setInterval(function () {
    $(".circle").each(function () {
        var color = '#' + (Math.random()*0xFFFFFF|0).toString(16);
        $(this).css("border", "10px solid " + color);
    })
}, 2000);

fiddle

Upvotes: 1

rfornal
rfornal

Reputation: 5122

What if something like this was done ... Start with a border and change the color randomly, but use a transition between colors on the border to allow for a smooth change.

CSS:

.circle {
    border: 10px solid blue;
}

JAVASCRIPT:

var i = setInterval(function () {
    var color = '#' + ((Math.random()*16777215) | 0).toString(16);
    $(".circle").css({
        transition : 'border-color 2s ease-in-out',
        borderColor: color
    });
}, 2000);

Tested ... jsFiddle

Upvotes: 1

Related Questions