Generating Tables of Contents with jQuery

For my FOM lecture on webprogramming I created a small jQuery example to automatically generate tables of contents. The following code just extracts h1-headings, using jQuery’s pseudoclasses („:header“) other extractions are of course possible.

Update 2015-06-21: I removed the ‚counter‘ variable, since ‚index‘ is already providing a counter.

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
<script type="text/javascript" src="jquery-2.1.1.min.js"></script>
 
</head>
<body>
 
<div id="toc"></div>
 
<h1>1st Headline</h1>
<h2>1st Subheader</h2>
 
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>
 
<h1>2nd Headline</h1>
<h2>2nd Subheader</h2>
 
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>
 
<h1>3rd Headline</h1>
<h2>3rd Subheader</h2>
 
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>
 
<script>
$(document).ready(function() {
	$("h1" ).each(function(index) {
		$(this).html($(this).html()+"<a name='lnk" + index +  "'></a>");
  	console.log(index + ": " + $(this).text());
  	$("#toc").html($("#toc").html() + "<br><a href='#lnk" + index + "'>" + $(this).text() + "</a>");
	});
}
);
</script>
 
</body>
</html>

autotoc

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website