Today I Learned - Rocky Kev

TIL how to get a random Hex color

POSTED ON:

TAGS:

// METHOD 1:
const generateRandomColor = () => "#" + Math.floor(Math.random()*16777215).toString(16);

// METHOD 2:
const randomHexColor = () => '#' + (0x1000000 + Math.random() * 0xffffff).toString(16).slice(1, 6);

generateRandomColor(); // Result: #fec150
randomHexColor(); // Result: #abba22
randomHexColor(); // Result: #304060

// Shove it on your body!
// document.getElementsByTagName("body")[0].style.color

toString(16) is using a radix param, so it's a hexadecimal.

let baseTenInt = 10;
console.log(baseTenInt.toString(2));
// Expected output is "1010"

2 for binary numbers,
8 for octal numbers,
10 for decimal numbers,
16 for hexadecimal numbers.

REFERENCE:
21 Useful JavaScript Snippets For Everyday Development
toString
Method 2 via


Related TILs

Tagged:

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL How to steal localData using an XSS attack

But that's just a red flag that opens the door to bigger issues.

TIL Clear-Site-Data

The Clear-Site-Data header clears browsing data (cookies, storage, cache) associated with the requesting website. It allows web developers to have more control over the data stored by a client browser for their origins.