advertisement

Listen Print Discuss

Make Internal Links Scroll Smoothly with JavaScript
Pages: 1, 2, 3, 4, 5, 6

Scroll, Don't Jump!

Now that we've identified an internal link, we want to scroll to it when it's clicked. To do this, we'll need to attach an onclick event handler to the link. In days of old, when web developers were bold, many thought that event handlers should be set on a link within the HTML:




<a href="http://www.sitepoint.com/" onclick="myEventHandler()">

This isn't really the truth; instead, you should attach an event listener to the link object. The W3C specifies a standard method to do this, as does Internet Explorer; Scott Andrew has usefully provided a function to handle both:


function addEvent(elm, evType, fn, useCapture)
// addEvent and removeEvent
// cross-browser event handling for IE5+,  NS6 and Mozilla
// By Scott Andrew
{
 if (elm.addEventListener){
   elm.addEventListener(evType, fn, useCapture);
   return true;
 } else if (elm.attachEvent){
   var r = elm.attachEvent("on"+evType, fn);
   return r;
 }
}

As we loop over the links, each matching link must have a new event handler attached to it for the "click" event. Then, when the link is clicked, it calls our smoothScroll() function instead of just navigating to the link as the browser normally would:


ss.addEvent(lnk,'click',ss.smoothScroll);

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

Next Pagearrow