- 1

Can we store colors in an array and use them randomly??

window.onload = function() { var h = 1; var w = 1; var con = document.getElementById('container'); var box = document.getElementById('box'); var p = document.createTextNode("FUCK"); /* i'm trying to repeat function zoom every 10 milisecs */ var t = setInterval(zoom, 1); var i = 1 ; function zoom() { /* if h >=200 and w >= 200 , the function zoom will be stopped */ if(h >= 200 && w >=200 ) { i = i* (-1); h +=i; w +=i; box.style.height = h; box.style.width =w ; box.style.background="green"; }else if ( w <=0 && h <= 0){ i = i* (-1); h +=i; w +=i; box.style.height = h; box.style.width =w ; box.style.background="yellow"; } else { /* else height and width will increase and the output makes you fell like it is enlarging */ h += i ; w += i ; box.style.height = h; box.style.width = w; } } }; THIS CODE SHOWS THAT A BOX ENLARGES AND WHEN IT REACHES THE MAXIMUM OR THE MINIMUM OF THE CONTAINER , IT SHOULD CHANGE THE COLOR , BUT I JUST CAN MAKE IT CHANGE 2 OTHER COLORS?? HOW TO GET MORE AND RANDOMLY?

7th Mar 2017, 5:04 PM
Thành Long
Thành Long - avatar
3 odpowiedzi
+ 18
arr=[]; for(let stp=0;stp<=20;stp++){ arr.push("#"+Math.round(Math.random()*16777215).toString(16)); }
7th Mar 2017, 7:10 PM
Valen.H. ~
Valen.H. ~ - avatar
+ 5
or alternative method, to generate a completely new color each time: var getRandomColor = function(){ /* taken from: http://stackoverflow.com/questions/1484506/random-color-generator-in-javascript */ var letters = '0123456789ABCDEF'; var color = '#'; for (var i = 0; i < 6; i++ ) { color += letters[Math.floor(Math.random() * 16)]; } return color; } i used this in one of my codes for color randomization
7th Mar 2017, 5:34 PM
Burey
Burey - avatar
+ 4
get random value in a range function function randVal(min, max) { return (Math.floor(Math.random()*(max - min + 1) + min)); } color strings array colorsArr = ["red", "green", "blue", "yellow", "purple"]; generate random color from the array color = colorsArr[randVal(0, colorsArr.length-1)]; box.style.background = color;
7th Mar 2017, 5:32 PM
Burey
Burey - avatar