1. Calculate Header Dimensions
When you click a link that points to a specific section (e.g., #contacts), the browser usually brings that section to the very top of the page. If you have a fixed menu at the top, it will cover the first few pixels of the section (often the title).
- What the script does: It calculates the height of your header (
#hdr) and subtracts that measurement from the final scroll position. This way, the section stops exactly below the menu.
2. Smooth Scrolling
Instead of an immediate, abrupt “jump” to the desired section, the script forces the browser to glide smoothly downward, improving the user experience.
3. Dynamic Link Management
It uses “event delegation” (document.addEventListener('click', ...)). This means the script also works on buttons or links loaded at a later time (e.g., via AJAX or dynamic widgets) without needing to reload the script.
4. Resolves Elementor Loading Issues
Page builders like Elementor sometimes take a fraction of a second to calculate the correct page heights.
- The solution in the code: The script includes “delays” (60ms, 350ms, and 500ms). If a user arrives at the site via a direct link to a section (e.g.,
yoursite.com/#services), the script waits for the page to be ready before scrolling, preventing the position from being incorrect.
5. Updates the URL Without Reloading
It uses history.pushState. When you click a link, the address in the browser bar updates (adding #section) without causing the flickering or jumping typical of standard browser behavior.
In summary, you need this if:
- You have a fixed header that covers section titles when you click on them.
- You want the scrolling to be smooth and elegant.
- You want links to work properly even when a user arrives at the page from an external link pointing to a specific anchor.
Technical note: If you change your header’s ID on the site, remember to modify this line in the code: const HDR_SELECTOR = '#hdr'; (replace #hdr with your header’s correct ID).
