Daniel Canna
Daniel Canna

Reputation: 43

Set css color based on a range

I'm generating a random number between 0 and 180 cycling every 4 seconds, successfully.

I need to set a div's background-color based on the random number. like

between 0 and 60 set css color to red, rgba(255, 0, 0, 1.0)

between 61 and 120 green, rgba(0, 255, 0, 1.0)

between 121 and 180 blue, rgba(0, 0, 255, 1.0)

So it all has to hinge on the variable... Any ideas...

Upvotes: 0

Views: 567

Answers (3)

Irfan Anwar
Irfan Anwar

Reputation: 1918

Run this code and click on box to get random colors

    $(window).ready(function() {

  $('#background').click(function() {

    var number = Math.floor((Math.random() * 180) + 0);
   console.log("random number is: "+ number);
    if (number <= 60) {
      $(this).css('backgroundColor', "rgba(255, 0, 0, 1.0)")

    } else if (number <= 120) {
      $(this).css('backgroundColor', 'rgba(0, 255, 0, 1.0)');
    } else {
      $(this).css('backgroundColor', 'rgba(0, 0, 255, 1.0)');
    }

  });
})
#background {
  width: 100px;
  height: 100px;
  background-color: rgb(255, 0, 255);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div id="background"></div>

Upvotes: 1

Nick Winner
Nick Winner

Reputation: 261

First of all, it's generally best to include your code in your S.O question to give your question some context.

That being said, the following should help you:

var ran // your random number
if (ran < 60) {
  $("div selector").css("color", "your color value here");
} else if (ran < 120) {
  $("div selector").css("color", "your color value here");
}

So on and so forth.

Upvotes: 0

ILCAI
ILCAI

Reputation: 1234

if (number <= 60) {
  $('#my-div').css('background-color', 'rgba(255, 0, 0, 1.0)');
} else if (number <= 120) {
  $('#my-div').css('background-color', 'rgba(0, 255, 0, 1.0)');
} else {
  $('#my-div').css('background-color', 'rgba(0, 0, 255, 1.0)');
}

... but, is this an answer? I guess, I didn't get your question well.

Upvotes: 0

Related Questions