Explain Codes LogoExplain Codes Logo

Anchor jumping by using javascript

javascript
prompt-engineering
web-development
best-practices
Nikita BarsukovbyNikita Barsukov·Nov 21, 2024
TLDR

To quickly navigate to an anchor using JavaScript, make use of the scrollIntoView() method:

document.querySelector("#yourDestination").scrollIntoView();

Please replace "#yourDestination" with the selector of your anchor to ensure quick and seamless scrolling through your webpage.

Tackling URL and focus: beneficial for users

Eliminating URL hash

Need a spotless URL devoid of any hashes after scrolling? This can help:

// Create a jump function function shipToAnchor(anchor) { history.replaceState(null, null, ' '); // Obliterate that pesky hash document.getElementById(anchor).scrollIntoView(); // Beam me up, Scotty! history.replaceState(null, null, anchor); // Return the innocent hash } // Propel the function shipToAnchor('yourAnchor');

Thanks to the power of history.replaceState, you can navigate, manipulate browser history, and keep things clean and tidy, just the way you like it.

Establishing focus for Web Accessibility

After you've landed on your anchor, managing focus is essential to cater to keyboard users and screen readers:

function beamAndFocus(anchor) { const heaven = document.getElementById(anchor); heaven.scrollIntoView(); heaven.tabIndex = -1; heaven.focus(); // 'Focus' is not just a Ford car model! } beamAndFocus('yourAnchor');

Setting a tabIndex of -1 allows focus on elements otherwise not accessible, making your website more inclusive.

Tailoring scroll positions: be the master

Precision navigation

Want that ultimate control over the scroll position? Here you go:

// Get the Y coordinates of the spacecraft const newYork = document.getElementById('yourAnchor').offsetTop; // Propel the ship to the height window.scrollTo(0, newYork); // Let's get high, but legally!

Aggregate offset calculation

Just the exact position of the nested elements? Try this:

function getSkyHigh(element) { let skyHigh = 0; while(element) { skyHigh += element.offsetTop; element = element.offsetParent; // Getting in touch with our forefathers } return skyHigh; } window.scrollTo(0, getSkyHigh(document.getElementById('yourAnchor')));

This loop calculates the total offset from the top, even for that corn-chip stuck between the keyboard keys.

Advanced URL manoeuvring through JavaScript

Clean URL update

After scrolling, you can programmatically update the URL without any page reload:

window.location.replace("#" + "yourAnchor"); // Deadlink? Resurrect with resurrection stones history.replaceState(null, null, window.location.href.replace(/#+$/, '')); // Vanity check, remove the trailing #

Backward compatibility considerations

Not every browser might be a fan of history.replaceState. Hence, always ensure backward compatibility:

if ('replaceState' in window.history) { window.history.replaceState(null, null, "freshURL"); } else { // It's alright, we got a plan B for reluctant browsers window.location.hash = "freshURL"; }

Preserving native webpage functionality

Preserving native anchor behaviour

Your custom jumping behaviour should augment, not replace. Here’s how you 'NOT break' the native anchor click:

// Look into all anchor tags document.querySelectorAll('a[href^="#"]').forEach(anchor => { anchor.addEventListener('click', function (e) { e.preventDefault(); // Let’s NOT do that! const targetID = this.getAttribute('href').substr(1); shipToAnchor(targetID); // Prepare for liftoff }); });

Robust anchor referencing

When you create anchors, add id attributes for strong referencing:

<div id="yourAnchor">Important thing you must see</div>

Remember, name attributes are as outdated as walkman tapes, it's id that rocks the stage now!