Automatically generate the table of contents with jQuery

Posted: Monday, February 01, 2010   # comments   


A few years ago, I wrote a table of contents generator in PHP for my development blog.

I am also using it for this site, which has been written in C# ASP.NET MVC. Rather than rebuilding a server side implementation, and considering that client side programming has been simplified with jQuery, I have decided to rebuild the script using jQuery. This allows anyone to add it to their page, regardless of their back-end language.

The implementation is below: (feel free to use it anywhere).

 
/*
The MIT License

Copyright (c) 2010 Robust Haven, Leblanc Meneses

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
// dependencies: jquery


if(!RobustHaven) var RobustHaven={};

if(!RobustHaven.Text) RobustHaven.Text={};

if(!RobustHaven.Text.TableOfContent) RobustHaven.Text.TableOfContent={};

RobustHaven.Text.TableOfContent = function(listtype) {
    this.listType = listtype;
    this.current = 0;
    this.toc = new Array();

    this.table = function(num) {
        var str = '';
        if (num > this.current) {
            for (var i = num; i > this.current; i--) {
                str += '<' + this.listType + '>';
            }
            this.current = num;
        } else if (num < this.current) {
            for (var i = num; i < this.current; i++) {
                str += '</li></' + this.listType + '>';
            }
            if (num != 1) {
                str += '</li>';
            }
            this.current = num;
        } else {
            str += '</li>';
            this.current = num;
        }
        return str;
    }

    this.getHtml = function(headings) {
        for (var i = 0, len = headings.length; i < len; i++) {
            var text = $(headings[i]).text();
            var anchorName = text.replace(/[^a-zA-Z0-9]/ig, '');
            $(headings[i]).attr('id', anchorName);
            var html = '<li><a href="#' + anchorName + '" title="' + text + '" style="text-decoration:none;">' + text + '</a>';
            switch ($(headings[i]).attr('tagName').toLowerCase()) {
                case 'h1': this.toc[i] = this.table(1) + html; break;
                case 'h2': this.toc[i] = this.table(2) + html; break;
                case 'h3': this.toc[i] = this.table(3) + html; break;
                case 'h4': this.toc[i] = this.table(4) + html; break;
                case 'h5': this.toc[i] = this.table(5) + html; break;
                case 'h6': this.toc[i] = this.table(6) + html; break;
                case 'h7': this.toc[i] = this.table(7) + html; break;
                case 'h8': this.toc[i] = this.table(8) + html; break;
                case 'h9': this.toc[i] = this.table(9) + html; break;
                default: break;
            }
        }

        var html = '';
        if (this.toc.length > 0) {
            for (var i = 0, len = this.toc.length; i < len; i++) {
                html += this.toc[i];
            }
            html += this.table(1);
        }

        return html;
    }
}


jQuery.fn.TableOfContentsBehavior = function(contentexpression, listtype) {
    if(listtype != "ul" && listtype != "ol")
        listtype == "ul";

    var headingElements = $('*', contentexpression)
        .filter(function(index) {
            var isHeadingExpression = /^h\d$/i;
            return isHeadingExpression.test(this.tagName);
        });

    var filter = new RobustHaven.Text.TableOfContent(listtype);
    var text = filter.getHtml(headingElements);
    $(this).attr('innerHTML', text);
}

Example page showing usage:

 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
	<html xmlns="http://www.w3.org/1999/xhtml">
		<head>
			<title>Auto generating the table of contents with jQuery</title>

			<!-- google's cdn for jquery -->
			<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js'></script>

			<!-- This is not a cdn url, copy the script and host it locally -->
			<script type='text/javascript' src='http://www.robusthaven.com/Content/js/TableOfContent.js'></script>
				
			<script type="text/javascript">
			$(function(e) {
				$('#TableOfContentsContainer')
					.TableOfContentsBehavior('div.article', 'ul');
			});
			</script>
		</head>
		<body>
			<div class='article'>
				<div id="TableOfContentsContainer"></div>
				<h1>Auto generating the table of contents with jQuery</h1>
				<h2>heading 2</h2>
				<p>content</p>
				<h3>heading 3</h3>
				<p>content</p>
				<h4>heading 3</h4>
				<p>content</p>
				<h5>heading 3</h5>
				<p>content</p>
				
				
				<h2>heading 2</h2>
				<p>content</p>
				<h3>heading 3</h3>
				<p>content</p>
				<h4>heading 3</h4>
				<p>content</p>
				<h5>heading 3</h5>
				<p>content</p>
			</div>
		</body>
	</html>

toc listed example output

PHP Implementation (for those interested)

While I don't program in php very much anymore here is the implementation that I wrote sometime in 2003-2004 time frame.

 
class CreateTableOfContents extends TextFilter{
	private $toc;
	private $current;
	private $listType;
	
   	public function __construct (TextProcess $pr, $listType) {
        parent::__construct($pr);
		
		$this->toc=array();
		$this->current=1;

		if( eregi('ul',$listType) ){
			$this->listType='ul';
		}else{
			$this->listType='ol';
		}
    }



	protected function preProcessing(TextVisitor $visitor){
		//The following expression needs a look ahead that doesn't capture 
		//the headings which have and id= already assigned to it.
		//Evaluates contents of parenthesis first
		$regex='/'. //start delimiter
					'('.
						'<'.
						   '('.
							   'h1|h2|h3|h4|h5|h6|h7|h8|h9'.
						   ')'.
						   '(?!id=(?:\"|\'))'.
						'>'.
						'(.*)'.
						'<\/'.
							   '\\2'.
						'>'.
					')'.
			   '/'; //end delimiter
		$cnt=0;
		while(  preg_match($regex, $visitor->_text)  ){
				// pattern, replacement, string, limit (limit is similar to =~s/ modifier in perl)
				// uses e modifier to send second captured group (.*?) to evaluate function
				// replaces first instance with whatever evaluate function returns
				$visitor->_text = preg_replace($regex.'e', '$this->evaluate("\\2", "\\3")', $visitor->_text, 1);
				
				if(++$cnt > 200){
					throw new InfiniteLoopException();
				}
		}
		
		$visitor->_text = $this->getTableOfContents().$visitor->_text;
    }
	
	protected function postProcessing(TextVisitor $visitor){}
	
	function evaluate($tag, $text){
		//remove all space instances in $text to create unique id name
		$text=strip_tags($text);
		$replacement = '<'.$tag.' id="'.preg_replace('/\s/', '', $text).'"'.'>'.$text.'</'.$tag.'>';
		$link = '<li><a href="#'.preg_replace('/\s/', '', $text).'" title="'.$text.'" style="text-decoration:none;">'.$text.'</a>';
		switch($tag){
			case 'h1': break;
			case 'h2': $this->toc[]=$this->table(2).$link."\n"; break;
			case 'h3': $this->toc[]=$this->table(3).$link."\n"; break;
			case 'h4': $this->toc[]=$this->table(4).$link."\n"; break;
			case 'h5': $this->toc[]=$this->table(5).$link."\n"; break;
			case 'h6': $this->toc[]=$this->table(6).$link."\n"; break;
			case 'h7': $this->toc[]=$this->table(7).$link."\n"; break;
			case 'h8': $this->toc[]=$this->table(8).$link."\n"; break;
			case 'h9': $this->toc[]=$this->table(9).$link."\n"; break;
			default;
		}
		return $replacement;
	}
	
	
	function table($num){
		$str='';
		if($num>$this->current){
			for($i=$num; $i>$this->current; $i--){
				$str.='<'.$this->listType.'>'."\n";
			}		
			$this->current=$num;
		}elseif($num<$this->current){
			for($i=$num; $i<$this->current; $i++){
				$str.='</li>'.'</'.$this->listType.'>'."\n";
			}
			if($num!=1){
				$str.='</li>';
			}
			$this->current=$num;
		}else{
			//equal ==
			$str.='</li>';
			$this->current=$num;
		}
		return $str;
	}
	

	
	

	
	function getTableOfContents(){
		$html='';
		if(count($this->toc)>0){
			foreach($this->toc as $key=>$value){
				$html.=$value;
			}
			$html.=$this->table(1)."\n";
			return $html;
		}else{
			return;
		}
	}
}
?>

PHP, jQuery, ASP.NET MVC, C#,