Explain Codes LogoExplain Codes Logo

Linking to a specific part of a web page

web-development
responsive-design
javascript
performance
Nikita BarsukovbyNikita Barsukov·Dec 24, 2024
TLDR

Jump to a page section by using an anchor link. Assign an id to the target element and then link it with href="#id".

  1. Designate an element with id:

    <div id="specifications">Specifications Here</div>
  2. Establish direct link to it:

    <a href="#specifications">Jump to Specifications</a>

Clicking the link brings the page to the <div> labelled "specifications".

Tackling named anchors and dynamic content

Once you're comfortable with the basics, you can venture into more complex territories like using named anchors and dealing with dynamic content. Named anchors utilize the name attribute of <a> tags, however, it is generally preferred to use the id attribute on any tag for linking.

When dealing with dynamic content such as AJAX-generated pages, JavaScript comes handy. The scrollIntoView() method works like a charm:

// "I'd scroll a thousand miles..." document.getElementById("ajax-content").scrollIntoView();

Combine it with JavaScript's setTimeout() function, if your content is loading or rendering asynchronously.

At times, the target page is not under your control, or it lacks required id attributes. Traditional linking methods can't be of much help here. But fret not, Chrome has a knight in shining armor for you - the #targetText= feature. This lets you link and highlight text on a page:

// "Find Waldo... err... your text here" http://mywebsite.com/pagename#targetText=Highlight%20Me%20Please

Though this is a neat Chrome feature, don't forget to cross-examine its compatibility with other browsers, and consider user privacy implications of automatically highlighting text.

Understanding browser behavior and respective scripts

Most modern browsers interpret internal linking in a similar fashion, but for a consistent user experience, testing your links across different browsers is a must. Leverage browser developer tools to find id attributes that can be utilized, or you might consider introducing them for better navigability.

Using JavaScript? Always refer to the detailed MDN documentation to confirm method and property compatibility. Pay attention to the window.open() function - some browsers might open a new tab instead of navigating in the same tab whilst using '_self', making your users feel like they're in a pop-up apocalypse.