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 mag LaTeX und Python, auch gern in Kombination. Hat Dir dieser Beitrag geholfen und möchtest Du Dich dafür bedanken? Dann unterstütze doch vielleicht die Dingfabrik Köln e.V. mit einem kleinen Beitrag. Details zur Bezahlung findest Du unter Spenden für die Dingfabrik.

More Posts - Website