How To Build an Alphabetical Page Index using jQuery




Most web developers are probably familiar with the anchor link solution for jumping to sections of the page. You can setup anchor links with a specific name attribute, and use the hash symbol as an href value to skip down the page. This effect has worked fantastic when listing very long sets of data. However the page jump isn’t exactly elegant and can sometimes throw off visitors, leaving them confused.

In this tutorial I want to explore a solution to this interface method. We will be creating a simple page index which uses anchor links as stepping stones on the page. However the “jump” will be animated and scroll down to reach the destination. I particularly enjoy this script because it is portable and easy to install into any website layout.

preview demo screenshot jQuery JavaScript scrolling index page links

Live DemoDownload Source Code

Spec the Layout

We can start off by creating the initial pages needed to get this script running. First is the basic index.html page which I am adding a typical HTML5 doctype. We also need to create two blank documents used later in the tutorial – styles.css for the page stylesheet and indexscroller.js for our custom jQuery codes.

In the document header I am also including the most recent version of jQuery from Google’s CDN hosting. Also a copy of the html5shiv trunk library for older browsers which do not support HTML5. In the body section I am using a custom Google Webfont named Milonga, along with some artistic CSS3 effects.

<!doctype html>
<html lang="en-US">
<head>
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
  <title>jQuery Alphabetical Scrolling Links Index</title>
  <meta name="author" content="Jake Rocheleau">
  <link rel="shortcut icon" href="http://spyrestudios.com/favicon.ico">
  <link rel="icon" href="http://spyrestudios.com/favicon.ico">
  <link rel="stylesheet" type="text/css" href="styles.css">
  <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Milonga">
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
  <script type="text/javascript" charset="utf-8" src="indexscroller.js"></script>
<!--[if lt IE 9]>
  <script type="text/javascript" src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>

Now the page layout will be styled as just a single column with TV show listings. Each show has its own div which contains a photo and some external links to Wikipedia and IMDB. At the very top of the page you’ll find a small box of links which are labeled A-G. These links will behave as our page index which scrolls down to the very first instance of that letter.

Main Body Contents

The entire body area is contained inside a wrapper div, which is split up by the header and TV show listings. The anchor link HREF values target indexes on the page which are listed alphabetically. So we start at #indexa ending with #indexg which are all targeting other anchor links on the page, using matching values for the name attribute.

  <div id="w">
    <h1>Dynamic jQuery Scrolling Links Index</h1>
    
    <div id="container">
      <nav id="links">
        <ul class="clearfix">
          <li class="label">Quick Links:</li>
          <li><a href="#indexa">A</a></li>
          <li><a href="#indexb">B</a></li>
          <li><a href="#indexc">C</a></li>
          <li><a href="#indexd">D</a></li>
          <li><a href="#indexe">E</a></li>
          <li><a href="#indexf">F</a></li>
          <li><a href="#indexg">G</a></li>
        </ul>
      </nav>

We can look at one example of the inline anchor links which can be found in-between TV show listings. I have left these anchors outside of any container since they don’t actually appear in the layout. These are in place right at the beginning of each new letter so that jQuery knows exactly where to stop scrolling.

<div class="show">
  <h2>Arrested Development <span class="meta"><a href="http://en.wikipedia.org/wiki/Arrested_Development_(TV_series)" target="_blank">Wikipedia</a> - <a href="http://www.imdb.com/title/tt0367279/" target="_blank">IMDB</a></span></h2>
  <p><img src="images/arrested-development.png" alt="Arrested Development TV Show" width="570" height="280"></p>
</div>

<a name="indexb"></a>
<div class="show">
  <h2>The Big Bang Theory <span class="meta"><a href="http://en.wikipedia.org/wiki/The_Big_Bang_Theory" target="_blank">Wikipedia</a> - <a href="http://www.imdb.com/title/tt0898266/" target="_blank">IMDB</a></span></h2>
  <p><img src="images/big-bang-theory.png" alt="The Big Bang Theory TV Show" width="570" height="280"></p>
</div>

Notice that before moving into the new letter, I have placed a single anchor using nothing more than its name attribute. We do not need any internal text or href value or anything else. Since we are following semantic HTML the user could also have JavaScript turned off and the fallback would still work properly, just like any generic anchor links.

CSS Page Styles

Some of the default stylesheet contents are really unique and helpful in this situation. Aside from the typical CSS resets I have also placed styles for positioning the body properly. I am using a small CSS3 box shadow on the body container so the layout stands out off the BG texture.

/* layout display styles */
#w { width: 620px; margin: 0 auto; padding-top: 55px; }

#container { 
  padding: 14px 20px;
  background: #fff;
  -webkit-box-shadow: 2px 2px 1px rgba(0,0,0,0.35);
  -moz-box-shadow: 2px 2px 1px rgba(0,0,0,0.35);
  box-shadow: 2px 2px 1px rgba(0,0,0,0.35);
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  border-radius: 5px;
}

Now for the TV show boxes I have included a few really important properties. Since the anchor links behave as stopping points in the page, I have included extra padding on the top of each TV show container. This way our scrolling effect doesn’t stop right at the top of each title, and there is some extra whitespace for breathing room.

/* tv shows display */
#shows { display: block; }

.show { display: block; padding-top: 8px; margin-bottom: 23px; }
.meta { font-family: Arial, Verdana, sans-serif; color: #222; font-size: 0.8em; font-weight: bold; float: right; }

/* clearfix */
.clearfix:after { content: "."; display: block; clear: both; visibility: hidden; line-height: 0; height: 0; }
.clearfix { display: inline-block; }
 
html[xmlns] .clearfix { display: block; }
* html .clearfix { height: 1%; }

Also the meta information is contained inside each header block, to save space in HTML markup. So we are floating this content and using a CSS clearfix to keep the layout in structure. With the layout design looking pristine, we should now move onto the final task of scripting the index animation effect.

jQuery scrollTop

This solution came together after searching online for a while and eventually stumbling upon this CSS-Tricks forum thread. jQuery has a method named .scrollTop() which can pull the current value in pixels from the top of the page to any other selected element. Using this technique we can determine the offset value for any TV show listing and naturally scroll down to that exact anchor link.

$(document).ready(function(){
  $('#links > ul > li > a').on('click', function(e){
    e.preventDefault();
    var anchorid = $(this.hash);
    
    if(anchorid.length == 0) anchorid = $('a[name="' + this.hash.substr(1) + '"]');
    else anchorid = $('html');
    
    $('html, body').animate({ scrollTop: anchorid.offset().top }, 450);
  });
});

So this is all the code you will find inside indexscroller.js. It doesn’t appear like too much, and it really isn’t all that complicated to follow. But let’s break down what happens after the DOM has finished loading.

After any of the internal #links anchors are clicked we immediately call e.preventDefault(). This will stop the hash values from appending onto the URL and jumping down the page instantaneously. Then using a new jquery.hash property we can pull the exact href value which comes after the hash symbol. So for example, our first index link would return a value of “indexa”.

Using this new value we can target the corresponding anchor link on the page with a matching name attribute. We setup this new anchorid variable and can now access the absolute number of pixels from the top using anchorid.offset().top. Finally adding all of this code into a simple jQuery .animate() method and we have our working index scroller.

jQuery scrollTop scrolling index anchor links

Live DemoDownload Source Code

Final Thoughts

This trick is perfect for web developers who are looking to increase the friendly-ness of any digital user interface. Websites are still in a very young stage of growth, yet advancing rapidly with the revolution of open source code. I applaud any developers who can put this script to good use, or even add onto it through additional functionality.

You can feel free to check out my live demo above and also grab a copy of the project source code. Everything should be easy enough to implement into your own layout, and all you need to change are the anchor link values. Additionally if you have any questions or comments on the tutorial you may share them with us in the post discussion area below.





About the author:

Jake is a creative designer, illustrator, and web developer. He frequently writes articles involving new-age design concepts and freelance management skills. You can find him in Google or follow his tweets @jakerocheleau

Comments:

Scroll back to the top