0

I'm trying to use the Jquery animate feature to change the background color of a div. If a random number is below 50 animate red and if higher than 50 animate green. Everything seems to work except for the color change. What I'm I doing wrong here?

function randomInt(min,max) {
    return Math.floor(Math.random() * (max - min + 1) + min);
}

if (randomInt(1, 100) > 50) {
    $('#status').html("win").animate({backgroundColor: "green" }, "fast");
} else {
    $('#status').html("lose").animate({ backgroundColor: "red" }, "fast");
}
Daniel
  • 4,202
  • 11
  • 50
  • 68

4 Answers4

0

You need to either use jQuery UI or a special color plugin to animate colors - unlike most other CSS properties.

http://plugins.jquery.com/color/

0

Probably not with jQuery animate() but with CSS3 transition.

CSS:

#status {
    -webkit-transition: background-color 2000ms linear;
    -moz-transition: background-color 2000ms linear;
    -o-transition: background-color 2000ms linear;
    -ms-transition: background-color 2000ms linear;
    transition: background-color 2000ms linear;
 }

jQuery:

function randomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min);
}

if (randomInt(1, 100) > 50) {
    $('#status').html("win").css({
        backgroundColor: "green"
    });
} else {
    $('#status').html("lose").css({
        backgroundColor: "red"
    });
}

See this jsfiddle.

But if you're really looking to do this with pure jQuery you can use jQuery Color which is more lighter than the whole UI Library.

Mark S
  • 3,789
  • 3
  • 19
  • 33
0

If you don't want to use Jquery UI or special plugin. **Just want to showcase "green" or "red" color then there is other working solution:

function randomInt(min,max) {
    return Math.floor(Math.random() * (max - min + 1) + min);
}
var status = $('#status');
if (randomInt(1, 100) > 50) {
    status.append("win");
    status.css({backgroundColor: 'green'});
} else {
    status.append("lose");
    status.css({backgroundColor: 'red'});
}
Gaurav Kalyan
  • 1,897
  • 2
  • 14
  • 21
0

Why don't you do it with simply JavaScript and CSS?

Just adding transition: background 1s to your CSS and using getElementById in JavaScript

Here's a Fiddle

ManelPNavarro
  • 579
  • 7
  • 21