I golfed this snippet slightly for no reason in particular. I recently posted a nice readable way to make random hsl colors. This snippet generates a random hexidecimal color.
How it works:
Math.random()// random number between 0 and 1
.toString(16)// convert to hex string (something like "0.2d6bcee4198d4")
One way to generate a random color is to randomize the hue argument of the css hsl. This value is in degrees 0-360 (colorwheel). The other arguments can be randomized as well if you need random saturation and lightness… like this:
document.body.innerHTML+='click to randomize background color';
const col = `hsl(${Math.random()*360}deg,50%,50%)`
e.target.style.background= col;
}
};
document.body.addEventListener('click', e =>{
// combine as many actions as we want
[...e.target.classList].forEach(cls =>{
const action = actions[cls];
if(action !=null) action(e);
});
});
This snippet takes the ideas from yesterdays post and goes one level further. This associates behavior with class names, so the class names can be combined to mix and match behavior.
In this case, combining classes like this green circle noBorder moveDown sayHi randomBgColor will cause the element in question to “move down”, “say hi” and randomize its background color when it is clicked. Click the “Try it out” to get a better idea.
I’m thinking about adding a little fake console to the Snippet Zone Quick Editor – just whipped this up as a proof of concept – something like this should work…