From c8894bb2b1ae3e994ea40815540966ffd88b88eb Mon Sep 17 00:00:00 2001 From: Harsh Shukla Date: Sat, 9 Nov 2024 21:40:32 +0530 Subject: [PATCH] Updated navbar.js added the debounce function and then wrapped the scroll event handler with it. --- navbar.js | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/navbar.js b/navbar.js index 7d794ed9..fb4da8f8 100644 --- a/navbar.js +++ b/navbar.js @@ -38,7 +38,18 @@ overlay.addEventListener("click", function() { overlay.style.visibility = "hidden"; }); -window.addEventListener("scroll", function() { +// Debounce function +function debounce(func, wait = 20) { + let timeout; + return function() { + const context = this, args = arguments; + clearTimeout(timeout); + timeout = setTimeout(() => func.apply(context, args), wait); + }; +} + +// Scroll event with debounce +window.addEventListener("scroll", debounce(function() { const navbar = document.querySelector(".navbar-collapse"); const navLinks = document.querySelectorAll(".navbar-nav .nav-item a"); @@ -53,7 +64,8 @@ window.addEventListener("scroll", function() { link.style.color = "#edf2f4"; }); } -}); +}, 20)); // 20ms delay for debounce + function toggleDropdown(show) { const dropdownMenu = document.querySelector('.dropdown-menu'); if (show) { @@ -61,6 +73,4 @@ function toggleDropdown(show) { } else { dropdownMenu.style.display = 'none'; } - } - - \ No newline at end of file +}