
This blog post is about the POC of the Random Color Picker tool, with this lightning web component we can generate the random colors and can copy the hex color code in the clipboard.
Let’s check how to generate the random color code:
backgroundColor;
backgroundColorCode;
getRandomColor(){
let x,y,z;
x = <strong>parseInt(Math.random()*255);</strong> //generate random integer numer in 255 range
y = <strong>parseInt(Math.random()*255);</strong>
z = <strong>parseInt(Math.random()*255);</strong>
let hexColorCode = <strong>"#" + this.componentToHex(x) + this.componentToHex(y) + this.componentToHex(z);</strong>
this.backgroundColorCode = hexColorCode.toUpperCase();
this.backgroundColor = 'background-color:' + hexColorCode;
}
componentToHex(c) {
<strong>var hex = c.toString(16);</strong> //convert the number into hexadecimal numbers
return hex.length == 1 ? "0" + hex : hex;
}
Generates random integer numbers in the 255 range.
parseInt(Math.random()*255);
Converts the number into hexadecimal numbers.
<strong>var hex = c.toString(16);</strong>
Finally in the below code snippet: append ‘#’ and concatenate all the hexadecimal numbers.
<strong>let hexColorCode = "#" + this.componentToHex(x) + this.componentToHex(y) + this.componentToHex(z);</strong>
Copy to clipboard function: This function copies the hex code in the clipboard.
copyToClipboard(event){
try{
<strong>//dynamically creating html component</strong>
var hiddenInputEle = document.createElement("input");
<strong>//get the title of clicked element (hex code)</strong>
let val = event.target.title;
<strong>//set value attribute </strong>
hiddenInputEle.setAttribute("value", val);
<strong>//append the element in the document body</strong>
document.body.appendChild(hiddenInputEle);
<strong> // select the content</strong>
hiddenInputEle.select();
<strong>// Execute the copy command</strong>
document.execCommand("copy");
document.body.removeChild(hiddenInputEle);
<strong> // show the toast meesage</strong>
const evt = new ShowToastEvent({
title: this._title,
message: this.message,
variant: this.variant,
});
this.dispatchEvent(evt);
}
catch(error){
<strong> //show toast message in case of error</strong>
const evt = new ShowToastEvent({
title: 'Error!',
message: 'Error has occured '+error,
variant: 'error',
});
this.dispatchEvent(evt);
}
}
Checkout GitHub repository of this tool here
Download the code from here

