From 0176dcef06ad1bd91a7e37dc4510c2d2af16f684 Mon Sep 17 00:00:00 2001 From: Imran Imtiaz Date: Sun, 28 Jul 2024 08:37:34 +0400 Subject: [PATCH] Update script.js By adding an event listener for DOMContentLoaded, the code now runs only after the DOM is fully loaded, ensuring that all elements are available for manipulation. Frequently accessed DOM elements are cached in variables to avoid multiple queries, improving efficiency. The loops have been optimized using forEach with an index to assign colors directly, which ensures the color array wraps correctly. Event handling has been made consistent by using addEventListener for attaching all event listeners. Additionally, the use of closest simplifies DOM traversal, enhancing readability and efficiency. --- script.js | 39 +++++++++++++++++++++------------------ 1 file changed, 21 insertions(+), 18 deletions(-) diff --git a/script.js b/script.js index 1ea72b0..a16ee50 100644 --- a/script.js +++ b/script.js @@ -1,23 +1,26 @@ -const container = document.querySelector(".container"); +document.addEventListener("DOMContentLoaded", () => { + const container = document.querySelector(".container"); + const openNavbarIcon = document.querySelector(".open-navbar-icon"); + const closeNavbarIcon = document.querySelector(".close-navbar-icon"); + const navLinks = document.querySelectorAll(".nav-link"); + const navigationButtons = document.querySelectorAll(".navigation-button"); + const colors = ["#6495ed", "#7fffd4", "#ffa07a", "#f08080", "#afeeee"]; -document.querySelector(".open-navbar-icon").addEventListener("click", () => { - container.classList.add("change"); -}); - -document.querySelector(".close-navbar-icon").addEventListener("click", () => { - container.classList.remove("change"); -}); + openNavbarIcon.addEventListener("click", () => { + container.classList.add("change"); + }); -const colors = ["#6495ed", "#7fffd4", "#ffa07a", "#f08080", "#afeeee"]; + closeNavbarIcon.addEventListener("click", () => { + container.classList.remove("change"); + }); -let i = 0; - -Array.from(document.querySelectorAll(".nav-link")).forEach(item => { - item.style.cssText = `background-color: ${colors[i++]}`; -}); + navLinks.forEach((item, index) => { + item.style.backgroundColor = colors[index % colors.length]; + }); -Array.from(document.querySelectorAll(".navigation-button")).forEach(item => { - item.onclick = () => { - item.parentElement.parentElement.classList.toggle("change"); - }; + navigationButtons.forEach(item => { + item.addEventListener("click", () => { + item.closest(".container").classList.toggle("change"); + }); + }); });