create a random color generator in javascript

index.tsx
function generateRandomColor() {
  // Generate random RGB values
  var 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 values
  var 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 element
var 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.

gistlibby LogSnag