DEV Community

Cover image for Random Hex Color (semi-golfed)
Zevan Rosser
Zevan Rosser

Posted on

4 1

Random Hex Color (semi-golfed)

document.body.innerHTML += 'click anywhere...'

onclick = () =>
  document.body.style.background = 
    `#${Math.random().toString(16).substr(-6)}`
Enter fullscreen mode Exit fullscreen mode

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")

.substr(-6) // grab the last 6 characters
Enter fullscreen mode Exit fullscreen mode

Here is a non-golfed version:

const instructionsEl = document.createElement('p');
instructionsEl.innerHTML = 'click anywhere...';
document.body.appendChild(instructionsEl);

const randomHexColor = () => 
  `#${Math.random().toString(16).substr(-6)}`;

document.addEventListener('click', () => {
  document.body.style.background = randomHexColor();
});
Enter fullscreen mode Exit fullscreen mode

See more stuff like this over @ Snippet Zone

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs