You are currently viewing Create A Random Color Palette Generator in HTML CSS & JavaScript
create-a-random-color-palette-generator-in-html-css-and-javascript

Create A Random Color Palette Generator in HTML CSS & JavaScript

A color palette is a collection of colors that are used together in a design or artwork. In web design, a color palette is a set of colors that are chosen to be used consistently throughout a website, to create a cohesive and visually pleasing look and feel.

Using a color palette in web design is beneficial for several reasons:

  1. Consistency: By using a consistent set of colors throughout a website, designers can create a sense of coherence and organization. This can help to improve the user experience, as users can quickly and easily navigate the site.
  2. Branding: A color palette can be used to reinforce a brand’s visual identity, by incorporating the brand’s colors into the website design. This can help to create a strong and memorable brand image.
  3. Accessibility: Using a carefully chosen color palette can help to ensure that the website is accessible to all users, including those with color vision deficiencies. By using colors that have a high contrast and are easy to distinguish, designers can create a website that is easy to read and navigate.
  4. Aesthetic appeal: A well-designed color palette can help to create a visually appealing website that is engaging and attractive to users. This can help to improve the overall user experience, and encourage users to spend more time on the site.

Overall, a color palette is an essential tool for web designers, as it can help to create a cohesive and visually appealing website that is easy to use and accessible to all users.

Here is a basic HTML, CSS, and JavaScript boilerplate template to get you started:

<!DOCTYPE html>
<html>
  <head>
    <title>My Website</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    <h1>Hello, World!</h1>

    <script src="script.js"></script>
  </body>
</html>

Add the following code in body section.

 <ul class="container">
        <li class="color">
            <div class="rect-box"></div>
            <span class="hex-value">#8A6CFF</span>
        </li>
</ul>
  1. <ul class="container"> – This is an unordered list (UL) element with a class of “container”. This element is used to group a set of list items (LI) together.
  2. <li class="color"> – This is a list item (LI) element with a class of “color”. This element represents each color in the color palette. We can have multiple LI elements to represent multiple colors.
  3. <div class="rect-box"></div> – This is a div element with a class of “rect-box”. This element represents the color box in the color palette. We can use CSS to style this box with a specific background color to represent the color in the palette.
  4. <span class="hex-value">#8A6CFF</span> – This is a span element with a class of “hex-value”. This element represents the hexadecimal value of the color in the palette. We can use JavaScript or server-side programming to generate the hexadecimal value for each color and insert it into this span element.
<button class="refresh-btn">Refresh Palette</button>

This is a code snippet for a button element with a class of “refresh-btn”. This button is commonly used in web applications to refresh or reload content dynamically without having to refresh the entire page.

Finally HTML displays as follows.

<ul class="container">
        <!-- <li class="color">
            <div class="rect-box"></div>
            <span class="hex-value">#8A6CFF</span>
        </li>
</ul>
<button class="refresh-btn">Refresh Palette</button>

Open the css file and add following code as follows

<link href="https://fonts.googleapis.com/css?family=Lato|Nanum+Gothic:500|Raleway&display=swap" rel="stylesheet">

This is a code snippet for adding external fonts to a web page using the Google Fonts API. Google Fonts is a popular service that provides a wide range of free web fonts that can be used in web design.

Here’s how to use this code snippet to add external fonts to your web page:

  1. Copy and paste the code snippet into the head section of your HTML document, preferably before any other CSS stylesheets or scripts:
  1. In the href attribute of the link element, specify the URL of the Google Fonts API, followed by a list of font families that you want to use on your web page. In this example, we are using three font families: Lato, Nanum Gothic, and Raleway.
  2. You can use the font family names in your CSS styles to apply the desired font to your HTML elements.
* {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: raleway;
        }

This is a CSS code snippet that applies to all HTML elements on a web page. It sets some common styles for all elements to ensure consistency in the layout and design of the page.

Here’s a breakdown of what each style does:

  • margin: 0: This sets the margin property of all HTML elements to 0. This removes any default margin that may be applied to elements by the browser, which can help ensure consistent spacing and layout across different devices and browsers.
  • padding: 0: This sets the padding property of all HTML elements to 0. Like margin, this removes any default padding that may be applied by the browser, ensuring consistent spacing and layout.
  • box-sizing: border-box;: This sets the box-sizing property of all HTML elements to border-box. This ensures that the width and height of an element includes any padding or border that may be applied to it. This can help prevent layout issues that can occur when padding or border is added to an element.
  • font-family: raleway;: This sets the font-family property of all HTML elements to “raleway”. This specifies the font family that should be used for all text on the page. In this case, “raleway” is the font family being used, but you can substitute it with any font family that you prefer.

Overall, this code snippet provides a good starting point for building a web page with consistent layout and design, and it can help save time by eliminating the need to specify these styles individually for each element.

body {
            background: #E3F2FD;
        }

This is a CSS code snippet that sets the background color of the body element of an HTML document.

Here’s a breakdown of what each style does:

  • body: This selects the body element of the HTML document. The body element represents the main content area of the page.
  • background: #E3F2FD;: This sets the background color of the body element to the specified color code, which is a light blue color (#E3F2FD). This will set the background color of the entire page to the specified color.
.container {
           display: flex;
           flex-wrap: wrap;
           margin: 20px;
           justify-content: center;
       }

related to the layout and positioning of its child elements. Let’s break down each of these properties in more detail:

  1. display: flex;: This property sets the container to use flexbox layout. Flexbox is a powerful layout model that allows you to control the alignment, distribution, and order of elements within a container. Once you set an element to display: flex, its child elements become “flex items” that can be positioned and sized using various flexbox properties.
  2. flex-wrap: wrap;: This property specifies how flex items should wrap when they exceed the width of the container. In this case, the value “wrap” indicates that flex items should wrap onto the next line if they can’t fit horizontally within the container. Without this property, flex items would continue to expand horizontally and potentially overflow the container.
  3. margin: 20px;: This property sets the margin around the container. The value “20px” indicates that there should be a 20-pixel margin on all sides of the container. This can help to create visual separation between the container and other elements on the page.
  4. justify-content: center;: This property controls the horizontal alignment of flex items within the container. The value “center” indicates that flex items should be centered along the main axis of the container. The main axis is determined by the flex-direction property, which is set to “row” by default (meaning that flex items are laid out horizontally from left to right).

So, in summary, the CSS code you provided sets up a container element that uses flexbox layout, wraps flex items onto multiple lines as needed, applies a 20-pixel margin around the container, and centers flex items horizontally within the container. This is a common pattern for creating flexible, responsive layouts that adjust to different screen sizes and content lengths.

.container .color {
           background: #FFf;
           list-style: none;
           margin: 13px;
           padding: 7px;
           border-radius: 6px;
           text-align: center;
           cursor: pointer;
           box-shadow: 0 10px 20px rgba(52, 87, 220, 0.08);
           transition: transform 0.3s ease;
       }

The CSS code you provided targets a specific element within a container element and specifies several properties related to its appearance and behavior. Let’s break down each of these properties in more detail:

  1. .container .color: This is a selector that targets all elements with the class “color” that are descendants of an element with the class “container”. This allows you to apply styles to specific elements within a container without affecting other elements on the page.
  2. background: #FFf;: This property sets the background color of the element to a light shade of white (#FFF). The background color is the color that fills the content and padding areas of an element.
  3. list-style: none;: This property removes the default bullet point or numbering from the element. This is useful for elements that are not lists, such as buttons or divs.
  4. margin: 13px;: This property sets the margin around the element. The value “13px” indicates that there should be a 13-pixel margin on all sides of the element. Margins create space around an element and can be used to control the layout of elements on the page.
  5. padding: 7px;: This property sets the padding within the element. The value “7px” indicates that there should be a 7-pixel padding on all sides of the element. Padding creates space within an element and can be used to separate content from the element’s border or background.
  6. border-radius: 6px;: This property sets the radius of the element’s border corners to 6 pixels. This creates a rounded appearance for the element’s corners.
  7. text-align: center;: This property centers the text content of the element horizontally. This is useful for elements such as buttons or headings that contain text.
  8. cursor: pointer;: This property changes the cursor style to a pointer when the user hovers over the element. This gives the user visual feedback that the element is clickable or interactive.
  9. box-shadow: 0 10px 20px rgba(52, 87, 220, 0.08);: This property adds a box-shadow to the element. The values “0 10px 20px” indicate that the shadow should be positioned directly below the element, with a blur radius of 20 pixels and a spread radius of 10 pixels. The last value, “rgba(52, 87, 220, 0.08)”, sets the color and opacity of the shadow. Box shadows can be used to add depth and dimension to an element.
  10. transition: transform 0.3s ease;: This property specifies a transition effect for the element. The value “transform” indicates that the transition should apply to the transform property (which controls transformations such as scaling or rotating an element). The value “0.3s” specifies the duration of the transition, and the value “ease” specifies the timing function for the transition. This creates a smooth, animated effect when the element is transformed.

So, in summary, the CSS code you provided sets up a specific element within a container with a light background color, no list-style, a margin and padding of 13 and 7 pixels respectively, rounded corners, centered text, a pointer cursor, a box-shadow with a blue color, and a smooth transition effect when transformed. This creates a visually appealing and interactive element that is consistent with other elements within the container.

.container .color:active {
            transform: scale(0.95);
        }

This CSS code targets the same element with the class “color” that we discussed earlier, but specifically applies a style when the element is in an “active” state. The “active” state refers to the moment when the element is clicked or touched by the user.

The code sets the “transform” property to “scale(0.95)”, which scales the element down to 95% of its original size. This creates a visual feedback that the element is being interacted with, as it appears to shrink slightly when clicked.

The “transform” property is a CSS property that allows you to apply 2D or 3D transformations to an element, such as scaling, rotating, or translating it. In this case, the “scale” function is used to scale the element down by a factor of 0.95, which reduces its size slightly.

Overall, this CSS code creates an interactive effect for the element when it is clicked, making it more engaging and responsive to user input.

.color .rect-box {
            width: 185px;
            height: 188px;
            background: #8A6CFF;
            border-radius: 5px;
        }

 

This CSS code targets a child element of the element with the class “color” that we discussed earlier, specifically one with the class “rect-box”. It applies several styles to this element:

  1. width: 185px;: This property sets the width of the element to 185 pixels. This controls the horizontal size of the element.
  2. height: 188px;: This property sets the height of the element to 188 pixels. This controls the vertical size of the element.
  3. background: #8A6CFF;: This property sets the background color of the element to a shade of purple (#8A6CFF). This creates a colored rectangle within the element.
  4. border-radius: 5px;: This property sets the radius of the element’s border corners to 5 pixels. This creates a slightly rounded appearance for the corners of the rectangle.

Overall, this CSS code creates a rectangular box within the element with the class “color”. The box has a specific width, height, and background color, and slightly rounded corners. This box can be used to display additional content or elements within the main element, such as text, images, or icons.

.color:hover .rect-box {
            filter: brightness(106%);
        }

This CSS code targets the same child element with the class “rect-box” that we discussed earlier, but specifically applies a style when the parent element with the class “color” is being hovered over by the user’s mouse pointer.

The code sets the “filter” property to “brightness(106%)”. The “brightness” function is a CSS filter that allows you to adjust the brightness of an element. In this case, the value is set to 106%, which slightly increases the brightness of the element.

When the user hovers over the parent element with the class “color”, this CSS code causes the child element with the class “rect-box” to become slightly brighter, giving it a subtle visual effect. This can help to make the element feel more interactive and engaging to the user.

.color .hex-value {
           display: block;
           margin: 12px 0 8px;
           font-size: 1.15rem;
           font-weight: 500;
           color: #444;
           text-transform: uppercase;
       }

specifically one with the class “hex-value”. It applies several styles to this element:

  1. display: block;: This property sets the display mode of the element to “block”. This causes the element to take up the full width of its container and start on a new line.
  2. margin: 12px 0 8px;: This property sets the top margin of the element to 12 pixels, the bottom margin to 8 pixels, and the left and right margins to 0. This creates some space between this element and other elements around it.
  3. font-size: 1.15rem;: This property sets the font size of the element to 1.15 “rem” units. This controls the size of the text within the element.
  4. font-weight: 500;: This property sets the font weight of the element to 500. This makes the text slightly thicker than normal.
  5. color: #444;: This property sets the text color of the element to a dark gray (#444).
  6. text-transform: uppercase;: This property sets the text of the element to be uppercase. This can help to create a consistent visual style for text elements within the page.

Overall, this CSS code creates a block-level text element within the parent element with the class “color”. The text element contains the hexadecimal color value for the main color of the element. The styles applied to this element help to control the appearance and layout of the text within the element, creating a consistent and visually appealing design.

.refresh-btn {
            position: fixed;
            left: 50%;
            bottom: 40px;
            outline: none;
            color: #fff;
            font-weight: 500;
            font-size: 1.1rem;
            padding: 12px 20px;
            background: #8A6CFF;
            border: 2px solid #fff;
            cursor: pointer;
            border-radius: 5px;
            box-shadow: 0 15px 25px rgba(52, 87, 220, 0.2);
            transform: translateX(-50%);
        }

This CSS code targets an element with the class “refresh-btn”. It applies several styles to this element:

  1. position: fixed;: This property sets the position of the element to “fixed”. This causes the element to be positioned relative to the viewport, rather than its parent element.
  2. left: 50%;: This property sets the left edge of the element to be in the horizontal center of the viewport.
  3. bottom: 40px;: This property sets the bottom edge of the element to be 40 pixels above the bottom edge of the viewport.
  4. outline: none;: This property removes the default outline that appears around an element when it is clicked or focused.
  5. color: #fff;: This property sets the text color of the element to white (#fff).
  6. font-weight: 500;: This property sets the font weight of the element to 500. This makes the text slightly thicker than normal.
  7. font-size: 1.1rem;: This property sets the font size of the element to 1.1 “rem” units. This controls the size of the text within the element.
  8. padding: 12px 20px;: This property sets the amount of padding around the text within the element. The top and bottom padding is set to 12 pixels, while the left and right padding is set to 20 pixels.
  9. background: #8A6CFF;: This property sets the background color of the element to a shade of purple (#8A6CFF).
  10. border: 2px solid #fff;: This property sets a white border around the element with a thickness of 2 pixels.
  11. cursor: pointer;: This property changes the appearance of the mouse cursor when it hovers over the element to indicate that it is clickable.
  12. border-radius: 5px;: This property sets the radius of the element’s border corners to 5 pixels. This creates a slightly rounded appearance for the corners of the element.
  13. box-shadow: 0 15px 25px rgba(52, 87, 220, 0.2);: This property adds a box shadow to the element with a horizontal offset of 0 pixels, a vertical offset of 15 pixels, a blur radius of 25 pixels, and a color that is a slightly transparent version of the purple background color of the element.
  14. transform: translateX(-50%);: This property applies a transformation to the element that moves it horizontally to the left by 50% of its own width. This centers the element horizontally within its parent element or the viewport.

Overall, this CSS code creates a button element that is fixed in position at the bottom center of the viewport. The button has a purple background color, white border, and white text color. When hovered over, it displays a slightly transparent box shadow. The button is centered horizontally within its container, and has a slightly rounded appearance due to the border radius. The styles applied to this element help to make it clear and visually appealing as a clickable button, while also making it easy to use and navigate within the page.

Finally our css file look like as follows
* {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: raleway;
        }

        body {
            background: #E3F2FD;
        }

        .container {
            display: flex;
            flex-wrap: wrap;
            margin: 20px;
            justify-content: center;
        }

        .container .color {
            background: #FFf;
            list-style: none;
            margin: 13px;
            padding: 7px;
            border-radius: 6px;
            text-align: center;
            cursor: pointer;
            box-shadow: 0 10px 20px rgba(52, 87, 220, 0.08);
            transition: transform 0.3s ease;
        }

        .container .color:active {
            transform: scale(0.95);
        }

        .color .rect-box {
            width: 185px;
            height: 188px;
            background: #8A6CFF;
            border-radius: 5px;
        }

        .color:hover .rect-box {
            filter: brightness(106%);
        }

        .color .hex-value {
            display: block;
            margin: 12px 0 8px;
            font-size: 1.15rem;
            font-weight: 500;
            color: #444;
            text-transform: uppercase;
        }

        .refresh-btn {
            position: fixed;
            left: 50%;
            bottom: 40px;
            outline: none;
            color: #fff;
            font-weight: 500;
            font-size: 1.1rem;
            padding: 12px 20px;
            background: #8A6CFF;
            border: 2px solid #fff;
            cursor: pointer;
            border-radius: 5px;
            box-shadow: 0 15px 25px rgba(52, 87, 220, 0.2);
            transform: translateX(-50%);
        }

 

Now open javascript file and add following code
const container = document.querySelector(".container");

    const refreshBtn = document.querySelector(".refresh-btn");

    const maxPaletteBoxes = 2000;

 

This is a JavaScript code snippet that creates three variables using the const keyword:

  1. container: This variable is assigned the value of the first element in the document that has a class of “container”. This is done using the document.querySelector() method, which returns the first element in the document that matches the specified CSS selector.
  2. refreshBtn: This variable is assigned the value of the first element in the document that has a class of “refresh-btn”. This is also done using the document.querySelector() method.
  3. maxPaletteBoxes: This variable is assigned the value of 2000. This variable is not based on any elements in the document, but is instead a constant value that will be used later in the code.

Together, these three variables are used to set up the functionality for a color palette generator. The container variable refers to the HTML element that will contain the generated color boxes, while the refreshBtn variable refers to a button element that will allow the user to refresh the color palette. The maxPaletteBoxes variable sets a limit on the number of color boxes that can be generated by the program. These variables will be used in later code to manipulate the page and generate the color boxes.

const generatePalette = () => { }

This is a JavaScript code snippet that declares a function named generatePalette() using the arrow function syntax. This function is defined, but does not yet have any functionality.

Functions in JavaScript are blocks of code that can be called and executed when needed. In this case, the generatePalette() function will be used to generate a new color palette when called.

The arrow function syntax is a shorthand way of writing functions in JavaScript that allows you to write the function’s code more concisely. It uses the => syntax to separate the function’s parameter list (if any) from its function body. In this case, the function does not have any parameters, so the parentheses after the function name are empty.

Now add following code in above function.

container.innerHTML = "";

In this code snippet, the container variable is an HTML element that will contain the generated color boxes. By setting its innerHTML property to an empty string, we are effectively clearing out any existing color boxes from the container element. This ensures that a new set of color boxes can be generated without any interference from previously generated boxes.

for (let i = 0; i < maxPaletteBoxes; i++) { }

This is a JavaScript code snippet that declares a for loop that will execute maxPaletteBoxes times.

In JavaScript, a for loop is a control flow statement that allows you to execute a block of code a specific number of times. It typically consists of three parts:

  1. The initialization expression, which sets the initial value of a loop variable. In this case, the initialization expression declares a variable named i using the let keyword and sets its initial value to 0.
  2. The condition expression, which checks whether the loop should continue executing based on some condition. In this case, the condition expression checks whether i is less than maxPaletteBoxes.
  3. The iteration expression, which updates the loop variable after each iteration. In this case, the iteration expression increments i by 1.

Inside the loop, we can include code that will execute on each iteration. In this case, the loop will be used to generate a new set of color boxes based on the current iteration number.

let randomHex = Math.floor(Math.random() * 0xffffff).toString(16);

This is a JavaScript code snippet that generates a random hexadecimal color value and assigns it to the randomHex variable.

In JavaScript, the Math.random() method returns a random decimal number between 0 and 1. By multiplying this value with the decimal value of 0xffffff, which represents the largest possible hex color value, we can generate a random number between 0 and 0xffffff.

The Math.floor() method is then used to round this random number down to the nearest whole number, ensuring that we get a valid hex color value. The resulting number is then converted to a string using the toString() method and specifying the radix of 16, which converts the number to a hexadecimal string.

The resulting hexadecimal string is assigned to the randomHex variable, which can then be used to generate a color box with a unique color value. By generating a new random hexadecimal value for each iteration of the loop, we can create a new set of randomly colored boxes each time the function is called.

randomHex = `#${randomHex.padStart(6, "0")}`;
            console.log(randomHex);

            //creating a new 'li' element and inseting it to the container
            const color = document.createElement("li");
            color.classList.add("color");

After generating a random hexadecimal color value and assigning it to the randomHex variable, the next lines of code are used to convert the value to a CSS color string, create a new li element for the color box, and add the color box to the container.

The line randomHex = #${randomHex.padStart(6, “0”)}; is used to convert the hexadecimal value to a CSS color string by adding a # symbol to the beginning of the string and padding it with zeros to ensure that it has six digits. This is necessary because CSS requires color values to be in the format #RRGGBB, where RR, GG, and BB represent the red, green, and blue components of the color, respectively. By adding a # symbol and padding the hexadecimal value with zeros, we ensure that the value will be in the correct format for use as a CSS color value.

The line const color = document.createElement("li"); creates a new li element that will be used to display the color box.

The line color.classList.add("color"); adds the color class to the li element. This is necessary because the CSS rules that define the appearance of the color boxes use the .color selector to target these elements. By adding the color class to the li element, we ensure that it will be styled as a color box.

The resulting li element is then ready to be styled and added to the container, which will display the new color box.

color.innerHTML = `<div class="rect-box" style="background:${randomHex}"></div>
            <span class="hex-value">${randomHex}</span>`;

After creating a new li element for the color box and adding the color class to it, the next line of code sets the inner HTML of the element to a string that includes a div element and a span element.

The div element has the class rect-box and its background CSS property is set to the randomly generated hexadecimal color value stored in the randomHex variable. This creates a rectangular color box with the randomly generated color.

The span element has the class hex-value and its text content is set to the value of the randomHex variable. This displays the hexadecimal color value below the color box.

By setting the inner HTML of the li element to this string, we create a color box with the color and hexadecimal value, which is ready to be added to the container and displayed on the page.

color.addEventListener("click", () => copyColor(color, randomHex));

This line of code adds a click event listener to the li element created for the color box.

The event listener function passed as the second argument to addEventListener calls the copyColor function with two arguments: the color element and the randomHex color value.

The copyColor function is a custom function not shown in the provided code snippet. It likely copies the color value to the clipboard or performs some other action when the user clicks on the color box.

By adding a click event listener to each color box, the user can interact with the color palette and copy color values as needed.

container.appendChild(color);

This line of code appends the newly created li element for the color box to the container element.

By calling the appendChild method on the container element and passing in the color element as an argument, the color box is added to the end of the container’s list of child elements.

This allows the newly generated color boxes to be displayed on the page and added to the existing color palette.

generatePalette();

This line of code calls the generatePalette function, which generates a new color palette and appends it to the container element.

By calling this function, a new color palette is generated and displayed on the page. This line of code is likely executed when the page is first loaded or when the user clicks a button to refresh the color palette.

const copyColor = (elem, hexVal) =>{

}

This code defines a function called copyColor that takes in two arguments: elem and hexVal.

The elem argument is a reference to the li element that was clicked by the user, while hexVal is the hexadecimal color value associated with that element.

const colorElement = elem.querySelector(".hex-value");

This line of code selects the HTML element with the class .hex-value that is a child of the elem element.

The querySelector method is called on the elem element, which should be the li element representing the color box that was clicked by the user.

By calling querySelector with the argument .hex-value, the function selects the span element containing the hex value of the color box. This element will be used to extract the hex value and copy it to the clipboard or perform some other action.

navigator.clipboard.writeText(hexVal).then(()=>{
          colorElement.innerHTML = "Copied";
          setTimeout(() => {
              colorElement.innerHTML = hexVal
          }, 1000);
      });

This code uses the Clipboard API to write the hexVal value (the hexadecimal color code associated with the clicked color box) to the clipboard.

The writeText method is called on the navigator.clipboard object and is passed hexVal as an argument. The writeText method returns a Promise that resolves when the text is successfully written to the clipboard.

Once the writeText Promise resolves, the text “Copied” is temporarily displayed within the colorElement element (which contains the hex value of the clicked color box). This message is displayed for 1 second (1000 milliseconds) before the colorElement is reverted back to its original hex value.

Overall, this code allows the user to click on a color box and copy its hex value to the clipboard. When the hex value is successfully copied, the colorElement displays the message “Copied” for a brief period before reverting back to the original hex value.

refreshBtn.addEventListener("click", generatePalette);

This code adds a click event listener to the refreshBtn button element using the addEventListener method. When the button is clicked, the generatePalette function is called to generate a new palette of random colors.

The generatePalette function is defined elsewhere in the code and is responsible for creating a new set of random color boxes and appending them to the .container element in the HTML document. By calling generatePalette when the refresh button is clicked, the user can easily generate a new palette of colors without having to manually refresh the page.

Finally our javascript file look like this

const container = document.querySelector(".container");

    const refreshBtn = document.querySelector(".refresh-btn");

    const maxPaletteBoxes = 2000;

    const generatePalette = () => {
       container.innerHTML = "";
        for (let i = 0; i < maxPaletteBoxes; i++) {
            //generating random hex color
            let randomHex = Math.floor(Math.random() * 0xffffff).toString(16);

            randomHex = `#${randomHex.padStart(6, "0")}`;
            console.log(randomHex);

            //creating a new 'li' element and inseting it to the container
            const color = document.createElement("li");
            color.classList.add("color");

            color.innerHTML = `<div class="rect-box" style="background:${randomHex}"></div>
            <span class="hex-value">${randomHex}</span>`;
            

            //adding click event to current li element to copy the color
            color.addEventListener("click", () => copyColor(color, randomHex));

            container.appendChild(color);
        }
    }
    generatePalette();

    const copyColor = (elem, hexVal) =>{
        console.log(hexVal);
        const colorElement = elem.querySelector(".hex-value");

        navigator.clipboard.writeText(hexVal).then(()=>{
            colorElement.innerHTML = "Copied";
            setTimeout(() => {
                colorElement.innerHTML = hexVal
            }, 1000);
        });


    }
    refreshBtn.addEventListener("click", generatePalette);

 

Print Friendly, PDF & Email

Leave a Reply