Create Background Color Changer Using Javascript
HTML code for Background Color Changer
<section> <button>Change BG Color</button> <h2></h2> </section>
There is all HTML code for Background Color Changer Now you can see output without CSS then we write CSS for our Background Color Changer.
CSS for Background Color Changer
* { padding: 0; margin: 0; box-sizing: border-box; } section { height: 100vh; width: 100%; display: flex; align-items: center; justify-content: center; flex-direction: column; } button { border: none; outline: none; background-color: aquamarine; font-size: 24px; font-family: "Montserrat"; padding: 20px; cursor: pointer; } h2 { font-family: "Montserrat"; font-size: 30px; margin-top: 30px; }
Now we complete our CSS section, Here is our updated output CSS.
Now add javascript for Background Color Changer!
Javascript for Background Color Changer
const button = document.querySelector("button"); const h2El = document.querySelector("h2"); const bgEl = document.querySelector("section"); // const hexColorEl = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"]; button.addEventListener("click", () => { let color = "#"; color += Math.random().toString(16).slice(2, 8).toUpperCase(); bgEl.style.backgroundColor = color; h2El.innerText = color; });
Now we complete our javascript section, Here is our updated output with javascript.Hope you like this Background Color Changer, you can see output video and project screenshots. See our other blogs and gain knowledge in front-end development.
Thank you
Hope you like this project, we create your own and use this project in any project as a part project like the reviews section, and a contact form. If you need any more project-related frontend. Visit our homepage and you get 100+ projects💝.
if you have any confusion Comment below or you can contact us by filling out our contact us form from the home section. 🤞🎉
written by – Codewithrandom
Hi