1
pimps
Tuesday, September 29, 2009 8:41:21 PM GMT

Automatically generate table of contents using jQuery

Automatically generate table of contents using jQuery
 
www.jankoatwarpspeed.com -- Some time ago, I was debating with my friends on the topic: is there any use of generating table of contents automatically. The conclusion was that it can be useful in cases when the reading material is long enough and table of contents (TOC) has a fixed position on the screen. This tutorial will show you how to create such TOC in just a few lines of code. Extract information from HTML I will start with the basic example - where we just want to get title and subtitles and show them before the article itself.          Title goes her     Subtitle goes here     Text goes here... Div element with "toc" id will be a container for TOC links (this can be also added dynamically but for this example, we'll keep it in static structure). The actual article is placed in div element with id "content". Check out demo 1 for full lorem ipsum article. Now let's create TOC. First we'll append a paragraph inside "toc" container with text "In this article". You might have seen this in some blog posts around. Next, we'll find all H1, H2 and H3 elements and assign unique id (for this page) to each one of them. This will make them easily accessible on click. At the end, we'll append a link for each heading. $("#toc").append('In this article:') $("h1, h2, h3").each(function(i) {     var current = $(this);     current.attr("id", "title" + i);     $("#toc").append("" +         current.html() + ""); }); The output of this code looks like this: In this article: Article title Header Level 2 Header Level 3 Header level 3 again Header level 3 once again And headings will have id's like in the example below: Article title View demo 1 Fixing TOC position In order to fix the position of TOC we have to do two things. First one is to wrap TOC and content into a div and center it on the screen (you can place TOC anywhere you like, but in this example we'll fix it to the left of the content). id="container">                   Title goes her         Subtitle goes here         Text goes here...      Next, set #to
beebee posted 170 days, 16 hours ago     show counter code
tags: Tutorials

No comments yet, be the first one to post comment.

To post your comment please login or signup