In the previous lecture we explored adding links that take you different web pages. Now we are going to work with Anchor Tags. Anchor tags allow us to link to a specific area of content on our existing page.
Let's take a look at an example. On this demonstration page, we have a table of contents at the top of the page that lists five articles. The idea is to have these items link to their corresponding article on the page. If I click on article three, for example, the page navigates to the beginning of the third article in our content area.
In order to make this work, we need to setup an anchor that will instruct the text link on the position of the article that corresponds to the link.
We have included a file called anchors.html in the downloads folder corresponding to this lecture. You will need to open this file in your text editor in order to follow along with this tutorial.
Let's go ahead and add anchors on all five Article Headings.
To add an anchor enter the following code, right before the article heading.
the id is the anchor name and you will see its significance when we add the anchor name to the text links.
Continue and add the other anchors in front of the remaining article headings:
Now that we have added named anchors, we will need to link the to them from our table of contents. Scroll up to the table of contents and add the following code around each article heading.
<a href="#article1">Article 1</a>
<a href="#article2">Article 2</a>
<a href="#article3">Article 3</a>
<a href="#article4">Article 4</a>
<a href="#article5">Article 5</a>
You will notice that unlike the links we added in the previous lecture, these links contain a # sign followed by the anchor name. The # sign instructs the browser not to divert the user to a new web page when this link is clicked. When the # sign is followed by an anchor name, the page will know to search for the anchor name on the existing page. It will then retrieve the content that is defined by the anchor position.
Save the page and open it in your web browser.
Click on each article and you will see that each link pulls up its corresponding article based on the positioning of the named anchors we created.
You will notice that when you click on article 5, the article does not pull up to the top of our content area. The reason is because the html content ends immediately after the article. In order for this to work, we would need to add additional breaks or paragraphs under the last article.