While working on the Bitbooks project (more detail to come on that later), I needed to automatically add anchoring links to page content that I didn’t create. By “anchoring links” (which name I completely made up since I don’t know what else to call them) I mean these link icons that you see in the content of some websites (like A List Apart or the Ruby docs).
These “links” point to the specific place on the page that you find them. That’s useful because when a visitor to the page can get a link to a specific place, they can refer to your document more accurately. This may not be helpful for linking to blog posts, where the whole post needs to be read for information to be understood in context, but many books or reference documents with long pages can really benefit by linking to specific sections where a topic can be discussed.
Once it’s included, you can use the addAnchors method to add anchors to your page. Here are a few brief usage examples:
/** * Example 1 * Add anchors to all h1's on the page */ addAnchors('h1'); /** * Example 2 * Adds anchors to elements containing the class '.anchored' */ addAnchors('.anchored');
And that’s pretty much it. You give it a selector, and it does the rest. If you want to see it in action, here’s the Live Demo.
AnchorJS is small (the .js file is 456 bytes minified) and has no dependencies. It comes with some default styles (that css file), but you can add your own, like if you really want to use a pilcrow (my new word of the day) instead of a link icon. If you want to learn more, go check out the project on Github.