How to Link to Specific Points in a Page and Animate the Scroll

by on 19th May 2011 with 17 Comments

You’ve seen it done before, you click a link in the navigation and it takes you not to another page but a specific point within the current page. How is this accomplished? With some extremely basic HTML that you can pick up in a few seconds!

To take it further, we’re also going to see how to animate the transition using a little jQuery.

Internal Linking: The Gist

As I explained in the intro, today we’re going to learn a basic trick and then see how to make it even better. When I was first learning web design, this was one of those things that I always told myself I needed to figure out but always put off learning, if you’re in the same boat, this article is for you.

Live Demo: Click Here

screenshot

A Tale of Two Links

As you can probably guess, linking to an internal section in your page requires not one but two links. First, you want to add the link that will serve as the anchor to scroll to, then you create the standard clickable link like you normally would and direct it at the first link. Make sense? If not, don’t worry, it’s easier than you think.

For the first part, let’s say we’re putting a link in a footer that will scroll to the top of the page, a common practice on longer pages. To insert this link, we use some syntax that you might or might not be familiar with:

Notice that instead of the typical “a href”, we used “a name”. This is important and is a likely point to get tripped up on if you’re used to inserting links with the former. You can pick anything you want for the name, just remember that it’s best to use something descriptive like we’ve done here. Also, make sure you take note of the name that you use, because we’ll have to refer to it again in the next step.

Once you’ve got that link all ready to go, it’s time to insert the anchor. Essentially, if you want to scroll to a specific point in a page, you have to insert a bit of code at that point so that the link we just created knows where to go.

Since we want to link to the top of the page, we would insert this snippet at the top of our HTML.


There are a couple of important things to take note of here. First of all, we added a hashtag to the beginning of the link name. This doesn’t appear in the first link, but it’s necessary in the second. Also, the text portion of this link has been left blank. This is not necessary, but is in fact an option. More often than not you’ll probably be linking to an element that is already in your layout so there will be content here.

Building the Demo

Now that you understand the syntax, it’s time to build a basic web page using what we’ve learned. Obviously, we’ll need to build a page that’s long enough to have to scroll. To this end, let’s start by tossing in some big blocks of text, each with its own headline.


 	

Headline One

Lorem ipsum dolor sit amet...

Headline Two

Lorem ipsum dolor sit amet...

Headline Three

Lorem ipsum dolor sit amet...

Headline Four

Lorem ipsum dolor sit amet...

The four headlines should provide us with four potential places to scroll to so we’re perfectly set up! From here we want to add in the named links the the h1 items.

Headline One

Lorem ipsum dolor sit amet...

Headline Two

Lorem ipsum dolor sit amet...

Headline Three

Lorem ipsum dolor sit amet...

Headline Four

Lorem ipsum dolor sit amet...

Starting CSS

Now we toss in some basic styling for this text. All I’ve really done is styled the fonts and added a bit of margin to each section to spread them out nicely.

* {
	margin: 0;
	padding: 0;
}

#container {
	width: 600px;
	margin: 50px auto;
}

/*Text Sections*/
.section {
	margin: 50px 0;
}

.section h1 {
	font: 55px/65px Helvetica, sans-serif;
}

.section p {
	font: 15px/25px Helvetica, sans-serif;
}

Here’s what the resulting paragraphs look like. Super simple but they’ll get the job done for what we need.

screenshot

Navigation and Header Image

To navigate to the anchors, we’ll need to create a series of links in our html using the hashtag method at the beginning of this article. We’ll also throw in a placeholder image just to give us a little more scrolling room.



Here we’ve created the text links with simple numerals and inserted the anchors to the various sections of our HTML. Now we just have to apply a little more styling and we’ll be ready to go.

/*Navigation*/

#nav {
	font: 12px/30px Helvetica, sans-serif;
	text-align: center;
}

#nav a {
	background: #444;
	color: #fff;
	margin-right: 30px;
	width: 30px;
	height: 30px;
	float: left;
	text-decoration: none;
	-webkit-transition: all 0.5s ease;
}

#nav a:hover {
	background: #6fcbf3;
}

/*Image*/
#bigPic {
	margin-top: 30px;
}

Basically what I’ve done here is turned each link into a little box:

screenshot

When you hover over one of the links, the background color transitions to blue. Notice that the line height on the text is set to the size of the box, this is a neat trick for centering the text vertically.

Clearing the Float

Since I wanted to turn the links into little boxes, I had to keep the display property set to block. This means to make the links line up horizontally, a float was necessary. There’s a lot of debate on how to clear floats these days, but a quick search revealed that the current favorite method seems to be the following from Pathfinder Software.

Feel free to disagree and implement your own float solutions. I won’t go any further into this so as to avoid distraction from the main purpose of this tutorial.

/* float clearing for IE6 */
* html .clearfix{
  height: 1%;
  overflow: visible;
}

/* float clearing for IE7 */
*+html .clearfix{
  min-height: 1%;
}

/* float clearing for everyone else */
.clearfix:after{
  clear: both;
  content: ".";
  display: block;
  height: 0;
  visibility: hidden;
  font-size: 0;
}

Finished Demo: Pure HTML/CSS

With that, our internal link demo is complete! Click any of the links in the navigation and they should take you to that point of the page. Notice that, for the anchors near the bottom of the page, the scroll just goes down as far as it can.

Live Demo: Click Here

screenshot

Animating the Scroll

With HTML, anchor linking works, but the transition is pretty harsh. There’s no animation at all, the page just jumps right to the anchor upon clicking. What if we want to make this a more gradual effect so the user can plainly see that the page is scrolling down?

You could perform the entire linking and scrolling operation in JavaScript, but I think that’s a bad idea simply because you’re unnecessarily limiting the number of people that can use your site to those with JavaScript turned on. Instead, it’s much better to set the linking up in HTML exactly like we’ve done here and then add the animation effect for JavaScript users. The site will still work for anyone with JS turned off, they just won’t see the animation.

To accomplish this, we need three things. The first is of course jQuery because it’s amazing and makes everything easier. The second is an extremely handy little jQuery plugin from Ariel Flesler called ScrollTo and finally, you’ll need an offshoot of ScrollTo called LocalScroll.

This sounds complicated but it’s super simple. LocalScroll was built for the sole purpose of animating anchor link scrolling so it’s the perfect tool for the job. It’s also by far the easiest solution to implement that I was able to find! The first thing you need to do is download LocalScroll and insert it along with jQuery into your HTML (ScrollTo will be included in the download as well).

 
 
 

Next we need to pass into it the parent element that contains the hashtag links. In our case the #nav div contains the links so we’ll insert that into the following snippet:


All you need to do to implement this in your own projects is change the target and, if you choose, specify a duration for the animation. That’s it! This one little block of text takes care of the animated scrolling effect for us.

Finished Demo: Animated with JavaScript

Here’s version two of our demo, this time with the JavaScript magic throw in. Compare it to the previous version to see how much nicer the effect feels with the transition.

Live Demo: Click Here

screenshot

Conclusion

In closing, remember that linking to a scroll point within your page is easy with pure HTML. All you need to do is set up a named link that is attached to a specific spot and a clickable link that will get you there.

After that, if you want to make the transition more gradual, use jQuery and LocalScroll together. Be sure to specify both the parent container for your links and the duration of the animation.

Comments & Discussion

17 Comments

  • http://www.pingdesigns.net David

    I’ve been wanting to try this out. Thanks for sharing. Great post!

  • http://jimmydid.it/ Jim

    awesome tutorial. but using these two jquery plugins for this simple effect is extreme overkill if you ask me. a lot of unused functionality.

    for something this simple, i’d use a lighter weight solution such as http://www.learningjquery.com/2007/10/improved-animated-scrolling-script-for-same-page-links which doesn’t require any plugins and only is just as simple to implement.

  • Joshua Johnson

    Thanks Jim! I looked forever to find a simpler solution. I definitely agree that three libraries for one simple effect is overkill! I just wanted something with a low barrier to entry that anyone could use. Good find!

  • Ralph

    Nice post. My only comment would be that using an element for the target is a bit old hat:

    Headline One

    ‘Twould be better to use

    Headline One

  • Ralph

    Sorry, HTML got parsed. Second try:

    My only comment would be that using an anchor element for the destination is outdated. Rather than

    h1 a name=”headline1″ Headline One /a /h1

    it’s better to use

    h1 id=”headline1″ Headline One /h1

  • komiska

    thanks for this great tut! it reminds me of a feature that i was wondering about – so is it possible to expand the tutorial some day? i wonder how to achieve the feature that eBay has – when you search for an item, and get the list result, if you click on an item, and then click “back to the search results” , it takes you exactly to the segment of the list you were looking at before clicking on an item… there must be something similar to an anchor tag going on …

  • Johny

    Can this be done from one page to another? So for example you click a link in the homepage that links to a Work Item in your portfolio page, so the page redirects to that especific item.

  • http://www.streeff.nl Evert Albers – Streeff.nl

    @Johnny: In plain HTML it can be done, but the jQuery stuff probably will not work.

  • Leslie CV

    Back Button question: since this is one page, the browser back button will take you out of the site. Is there a way to create a “back” link inside the site to compensate? This link would take you to the section/anchor you were just in. (note: I am using an ever-present menu with my one page site) Thanks!

  • http://www.boostinspiration.com Waheed Akhtar

    Thanks for this post. After reading this, I got something fixed on my personal website (http://www.crea8iveart.com). It really helped.

  • http://omgmog.net Max Glenister

    Nice article, however the effect can be pulled off with just the jQuery library alone and a bit of well-crafted JavaScript. No need for the additional plugins.

    One other point, it’s probably better or more correct to use the “id” attribute rather than “name”, it will work just the same. http://www.w3.org/TR/html401/struct/links.html#h-12.2.3

    Lastly, the addition of a “back to top” link or a persistent menu would be a nice touch :)

  • http://www.RobustTech.com Scott Tweedie

    The Back to Top links at the top of this article, will not work, and could confuse a new web designer. You probably just typed it wrong by mistake.

    I think you meant to say:

    …let’s say we’re putting a link in a footer that will scroll to the top of the page

    Back To Top

    Since we want to link to the top of the page, we would insert this snippet at the top of our HTML:

    …When the user clicks Back to Top, it will link to the anchor named “linktotop”

    It may be useful to first explain that the tag has two two purposes:

    1-To create a link to another document, by using the href attribute
    2-To create a bookmark inside a document, by using the name attribute

    Thank you-
    Scott Tweedie

  • Henrik Karlsson

    Thanks for this post!

    I followed the instructions but for some reason I can´t get it to animate. Anyone having any ideas on what could be wrong in my code?

    Here´s a link to the WIP site:
    http://differentshadesofgrey.com/html_new/

    Thankful for help!

    Henrik

  • Henrik Karlsson

    Dissregard my last comment. Works fine now!

  • http://www.twitter.com/rovanion Rovanion

    You should add add hash:true to the array you send to localScroll. That way the hashes appear on the top of the page and linking to a specific part of the text works.

  • http://www.couponsforindia.com/greendust.com/ Greendust Coupons

    Great Post very informative and very well written
    Thanks for Sharing;-)

  • heman

    thanks for this great tut! it reminds me of a feature that i was wondering about – so is it possible to expand the tutorial some day? i wonder how to achieve the feature that eBay has – when you search for an item, and get the list result, if you click on an item, and then click “back to the search results” , it takes you exactly to the segment of the list you were looking at before clicking on an item… there must be something similar to an anchor tag going on …
    Read more at http://designshack.net/articles/html/how-to-link-to-specific-points-in-a-page-and-animate-the-scroll/#WEySo685TCz9zKFZ.99

Subscribe
Membership
About the Author