HTML has always had the ability to link to the location of other elements on a page, referred as anchor links. If any element has an id attribute:
<h3 id="point3">Heading</h3>
Then you can jump to the location of that element from a link on the same page by referencing the value of the id:
<a href="#point3">Jump to the location of Point 3</a>Obviously, we need a page that has plenty of content to make this technique work: if the browser already displays all of the page’s content, no jump will take place. For that reason, anchor links are usually reserved for long reads that are divided into sub-sections, or single page sites. (For the same reason, you’ll need to ensure that any test page you try to apply this code to has plenty of filler text).
In all current browsers the jump between link and anchor will be instant. With web interfaces increasingly featuring easing effects, it makes sense for designers to desire a smoother transition during the jump. CSS will not help us there: CSS cannot animate page scrolling. Instead, we must turn to JavaScript; for ease of use and compact code, I’ve chosen to use JQuery (here, I’m assuming the use of JQuery 1.8.1 or above, with a hat-tip to Paulund):
<script src=//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js></script>
<script>
$(document).ready(function() {
$('a[href^="#"]').on('click.smoothscroll',function(e) {
e.preventDefault();
var target = this.hash,
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 500, function () {
window.location.hash = target;
});
});
});
A quick discussion of the code. Attribute pattern detection is something we’ve already discussed; on binds DOM events (such as click, submit, or a custom event name) to JQuery in a way that the script is always on the lookout for the event, and will fire off the sequence of code that follows in response.
e.preventDefault stops the browser from taking normal actions: in this case, it stops the immediate jump to the anchor, allowing us time to animate the transition.
this.hash is another string detection property: it looks at the link’s href attribute value and extracts the # part of the URL. For our example link above, this.hash would be #point3.
$('html, body’).stop().animate clears JQuery’s animation queue, then initiates an animated scroll to the location of the targeted id over half a second (500 milliseconds). The animation will include easing automatically, just as CSS3 does.
This technique will often be combined with site navigation elements that have a fixed position, following the user’s exploration of the page, possibly including its own“scroll to top then fixed” effect.
Pro CSS3 Animation, Apress, 2013