JQuery Math for color animation - specific color range

I use this math to animate the bg color on hover:

var col = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')'; 

It produces random rgb color. Very nice, but I'm looking for something else.

Does anyone know a good math that I can use to have a random color from only a certain range of colors, like red or green?

Any help is appreciated.

@Avinash, here is my full code as I am using it right now. How can I enable your solution?

 $(document).ready(function () { //bg color animation original = $('.item,.main-menu-button').css('background-color'); $('.item,.main-menu-button').hover(function () { //mouseover var col = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')'; //random hover color $(this).stop().animate({ 'backgroundColor': col }, 1000); }, function () { //mouseout $(this).stop().animate({ 'backgroundColor': '#111' }, 500); //original color as in css }); }); 



This does not work. I'd rather leave it as it is. Thank you all for your help.

+4
source share
3 answers

To create a random number in a range, we need to do something like

 minValue + random Number * (maxValue - minValue) 

ie, if you want to create a random number between the range of 100 to 200 , we must do

 var rand = 100 + Math.floor(Math.random() * (200 - 100)); 

which gives a random number between the range of 100-200

using this basic rule, we can generate random color from a given range

 var range = [{0 : 150,1 : 200}, {0 : 200,1 : 230},{0 : 10,1 : 20}]; function rgb() { var color ='rgb('; for(var i = 0; i< 3; i++) { color += rand(range[i]['0'], range[i]['1']) + ','; } return color.replace(/\,$/,')') } function rand(min, max) { return min + Math.floor(Math.random() * (max - min)); } alert(rgb()); 

Try this code http://jsbin.com/tuday

EDIT :

 $(function() { var cache = $('#hover').css('background-color'); $('#hover').hover(function() { $(this).css({'background-color' : rgb() }); },function() { $(this).css({'background-color' : cache }); }); }); 

Example : http://jsbin.com/iwovew

+6
source

Creates a random color from the black-red range:

 var col = 'rgb(' + (Math.floor(Math.random() * 256)) + ',0,0)'; 
+3
source

You should study the conversion of values ​​to RGB and from RGB to HSB (sometimes called HSI). Arithmetic on this color model makes a lot of sense. For instance. To play with red shades, you can start with HSB values ​​(0, 100, 100) for pure red. Changing S = 50% gives you a β€œgray” shade of red. Changing B = 50% gives you a β€œdark” shade of red.

+1
source

All Articles