When creating markup for longer written pieces on a single page, it's often important to create navigational structures to jump between different portions of that text. This is supported natively in HTML, allowing us to skip to sections within a page and even visit them directly from external links.


In this tutorial, we'll discuss a technique for dynamically generating those links with JavaScript, and then animating them using CSS. Let’s dive in!
Markup
The first necessary step is to create suitable markup for your written piece. We'll assume that you have an article
, and inside that article there are many section
s, each with its own h1
tag and subsequent content.
Here’s what your HTML might look like:
<article> <section id="part-one"> <h1>Here’s one part</h1> <p>Mobilize pride fundraising campaign, foundation criteria save lives human rights donate empowerment. Generosity climate change, vulnerable population global leaders lasting change. Outcomes, honesty developing nations disruption human-centered design; progress implementation UNHCR many voices process.</p> <p>The Elders; complexity celebrate; legal aid diversification sanitation social entrepreneurship open source assistance contribution community health workers. </p> </section> <section id="part-two"> <h1>Here’s another</h1> <p>Expanding community ownership; Kickstarter public service collaborative consumption, employment Rockefeller public-private partnerships transformative tackling. Partner Aga Khan informal economies necessities collaborative cities public institutions opportunity nutrition.</p> </section> <section id="part-three"> <h1>And yet one more</h1> <p>Public sector free expression meaningful, enabler; Andrew Carnegie Bloomberg, emergent involvement globalization crisis situation. Gender, gender equality truth long-term improving quality youth civic engagement equality scalable end hunger sustainable Medecins du Monde agency change lives.</p> <p>Social analysis, affiliate; cornerstone life-saving grantees Jane Addams free-speech, change movements lifting people up social challenges positive social change disruptor future.</p> </section> </article>
Note: as you can see, we are applying an id
to the separate sections. We choose to do this because the id
is actually related to the section itself, not the h1
tag.
To jump to an element with a given id
on a page, you create an anchor tag with an href
value equal to the hash mark followed by the id
. For instance, in our example content from above, to jump to the second section, we could create the following link:
<a href="#part-two">Second section</a>
There are plenty of ways to do this: you could code the links in by hand, you could use an abstraction that builds out your section HTML, including the link. In this tutorial, however, we’re going to use JavaScript to generate the links dynamically.
Vanilla JS
Here’s the JavaScript:
var sections = document.querySelectorAll('section'); for (var i = 0; i < sections.length; i++) { var section = sections[i]; var id = section.id; var h1 = section.querySelectorAll('h1')[0]; var text = h1.innerHTML; h1.innerHTML = "<span>" + text + "</span>" + "<a href='#"+ id +"'>"+ id +"</a>"; }
jQuery version
And here’s a jQuery version, essentially achieving the same thing:
$('article section').each(function(i,el){ var id = $(this).attr('id'); var h1 = $(this).find('h1').first(); var t = h1.text(); h1.html("<span>" + t + "</span>"); h1.append("<a href='#"+id+"'>#"+id+"</a>"); });
Both of these give the same result. We look for all of a given article’s section descendants, and for each of those we find the id
of that section. Then, we build a link which points to that id
and append it to the header
element. We also wrap the existing text in a span for more flexible styling.
Speaking of Styling…
Next, let’s apply some basic CSS to provide a hide and reveal effect:
@import url(http://fonts.googleapis.com/css?family=Fira+Sans:300,400,700); body { font-family: "Fira Sans", sans-serif; color: #444; } article { width: 90%; margin: 0 auto; } h1 { position: relative; span { float: left; } a { transition: all .4s; opacity: 0; color: #FD9148; font-weight: 300; margin-left: 12px; text-decoration: none; } &:hover { a { text-indent: 0; opacity: 1; } } }
These rules first set some basic styles; font
, color
, article width
and so on. Then we state that the a
(which we appended earlier via JavaScript) will have transitions applied to it and will have an opacity of 0 by default. Only when we hover over it does its opacity increase to 1, giving us the fade in effect.
And that’s it! Now we have a relatively simple implementation of this technique in action:
Conclusion
We’ve just built a really useful enhancement for content rich web pages! The fallback is graceful too: if JavaScript is disabled, the links simply don’t appear–and if a hash tag is present at the end of the url it’s ignored.
Our fade-in effect is a simple way of presenting the link, so how could you improve it? What kinds of animations could you apply? Would you position the link in the same way? We look forward to hearing your ideas (and watch out for the community project we’ll shortly be launching on this very subject!)
Envato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!
Translate this post