The code at first looks terrible. Let simplify it step by step.
//find 1st <button> element and assign on'click' handler to it
document.querySelector("button").addEventListener("click", function(){
document.body.style.background = randColor();
//background is the **result** of execution of randColor()
})
function randColor(){
return '#' + (function co(lor){ return (lor +=
[0,1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f'][Math.floor(Math.random()*16)])
&& (lor.length == 6) ? lor : co(lor); })('');
}
randColor()
returns an expression which includes a function (in fact, IIFE
).
Let put the result instead of function call. Meanwhile, parenthesis around the function can be omitted here because of +
operator before.
document.querySelector("button").addEventListener("click", function(){
document.body.style.background = '#' + function co(lor){
return (lor +=
[0,1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f'][Math.floor(Math.random()*16)])
&& (lor.length == 6) ? lor : co(lor); }(''/*send empty string to lor parameter*/);
})
Still not easy? Let's take next step.
document.querySelector("button").addEventListener("click", function(){
document.body.style.background = '#' + co(''/*send empty string to lor parameter*/);
})
function co(lor){
return (lor += /*assignment returns the new value. always truey in this case*/
[0,1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f'][Math.floor(Math.random()*16)/*magic 16 is the array length*/])
&& (lor.length == 6) ? /*returns when we have 6 character string*/lor : /*call the function recursively*/co(lor);
}
And final simplification. Use a loop instead of recursion.
function co(){
var lor = '';
var hexDigits = '0123456789abcdef'.split('');
for(var i = 0; i < 6/*required length*/;i++){
lor += hexDigits[Math.floor(Math.random() * 16)/*0 - 15*/];
}
return lor;
}
Leading #
makes up correct HEX
value for the color.