This code snippet allows you to dynamically generate a color palette using JavaScript. By providing an array of hexadecimal color codes, this code generates a visual representation of the colors on a web page. It iterates over the color array, creating a div element for each color and setting its background color accordingly.
Additionally, it appends a label displaying the color code below each color div. This code is helpful if you need to showcase a set of colors or create a user interface that requires a color palette.
How to Create JavaScript Generate Color Palette
1. Create the HTML structure for the color generate palette as follows:
<h2>Color Palette</h2> <p>This is a quick demo of a tool that takes an array of hex codes and uses it to generate a color palette with Vanilla JS. It would be neat to add an input box so the user can enter the colors.</p> <div id="root"> </div>
2. Now, style the generated color palettes using the following CSS styles:
html { background-color: #cfcfcf; font-family: Calibri; } h2 { text-align: center; font-size: 22px; } p { max-width: 480px; margin: 0px auto; margin: 0px auto 20px auto; } div#root { display: grid; grid-template-columns: repeat(auto-fill, minmax(100px, 1fr)); grid-gap: 20px; margin: 0px auto; max-width: 460px; } div#root > div { width: 100px; border: 1px } div#root div.label { text-align: center; margin-top: 5px; } div#root div.color { width: 100px; height: 100px; }
3. Finally, add the following JavaScript function for its functionality:
let colors = ['#4daf7c','#e8dab2','#dd6e42','#f46d7a','#4f6d7a','#eafafa','#736598','#3498db']; let root = document.querySelector('#root'); for (var i = 0; i < colors.length; ++i) { let color = document.createElement('div'); color.style.backgroundColor = colors[i]; color.className = 'color'; let con = document.createElement('div'); let txt = document.createElement('div'); txt.className = 'label'; txt.textContent = colors[i]; con.appendChild(color); con.appendChild(txt); root.appendChild(con); }
That’s all! hopefully, you have successfully integrated this JavaScript code into your project to generate color palettes. If you have any questions or suggestions, feel free to comment below.