Make Internal Links Scroll Smoothly with JavaScript

by Stuart Langridge, author of DHTML Utopia (SitePoint)

When they're navigating through a long document, users often are confused or disoriented when they click on a link that jumps to another location in that same document.

Are they on the same page, or a different page? Should they scroll more from here? What's going on?

The answer to this problem is to scroll the user through the document to the linked location, as you can see from this demo. In this tutorial, we'll use a smattering of JavaScript to ensure that links that are internal to the document scroll users to their destinations, rather than jumping straight there and confusing site visitors.

Finding Internal Links

First, we need to identify all the links in the document, and work out which of them are internal links. Getting a list of all the links is easy:

 var allLinks = document.getElementsByTagName('a');

We need to walk through this list, and work out which of the links are internal. An internal link will have a hash (#) symbol in it, and it will point to the document we're currently looking at. The useful location object tells us about the URL of the current document, so try this:

 for (var i=0;i<allLinks.length;i++) {
 var lnk = allLinks[i];
   if (
         (lnk.href && lnk.href.indexOf('#') != -1) &&  
         (lnk.pathname == location.pathname) 
       ) || (
         ('/'+lnk.pathname == location.pathname) ) &&  
         ( ==
      ) {

The for loop walks through the list of links in the document; we check three things:

  1. Does the link contain a hash symbol? To check this, we use the link's href property and the indexOf() function to find the location of one string in another.
  2. Is the link the same as the current location? Links (and the location object) have a pathname attribute. The pathname of the URL is /about/who/mharbottle.php in some browsers, and about/who/mharbottle.php in others (note the presence or absence of the first slash). We must check for both.
  3. Is the query string the same as the current location? The query string is everything that appears after the ? in a URL; this is obviously important if your site is database-driven. JavaScript defines a search attribute on location and links that contain the query string.

If the answer to each of these questions is yes, then we know the link is an internal one, and we can set it to scroll to its destination rather than simply navigate there.

DHTML Utopia

Related Reading

DHTML Utopia
Modern Web Design Using JavaScript and DOM
By Stuart Langridge

Pages: 1, 2, 3, 4, 5, 6

Next Pagearrow