functiongenerateRandomColor() {
// Generate random RGB valuesvar r = Math.floor(Math.random() * 256);
var g = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);
// Create hexadecimal color code from RGB valuesvar colorCode = "#" +
r.toString(16).padStart(2, "0") +
g.toString(16).padStart(2, "0") +
b.toString(16).padStart(2, "0");
return colorCode;
}
// Generate and apply random color to HTML elementvar myElement = document.querySelector("#my-element");
var randomColor = generateRandomColor();
myElement.style.backgroundColor = randomColor;
608 chars
20 lines
This code generates a random color by generating random RGB values and then creating a hexadecimal color code from them. The color code is then applied to an HTML element using the style property.