Shoora
4/28/2019 - 11:21 AM

Create a clickable index list from all heading elements on a page.

Create a clickable index list from all heading elements on a page.

/*
 * Assuming your post/page content happens in .entry-content and you structured it semantically using h3 elements,
 * these functions will create a clickable index list at the top of your content.
 * Modify hard-coded selectors as you see fit; I used .indexlist for the ul element, 
 * .indexitem for each li item and h3 elements within .entry-content to create the list items from.
*/
	$.fn.inlineScrolling = function(options) {
	
		return this.each(function(event) {
			
			var $this = $(this);
	
			$this.on('click', $this, function(event) {
				var scrollTarget = $( '#' + this.href.split( '#' )[ 1 ] ).offset().top;	
				$( 'html, body' ).animate( {
					scrollTop  : scrollTarget
					}
					, 250);
				event.preventDefault();
				return false;
			});	
		});
	}
	
	$(document).ready(function(){
	
		$( '.entry-content' ).prepend('<ul class="indexlist"></ul>');
		$( $( '.entry-content h3' ).get().reverse() ).each(function(index){
			var itemindex = ( index + 1 );
			$( this ).attr( 'id', 'indexitem-' + itemindex ).before( '<br /><hr />' );
			$( '.indexlist' ).prepend( '<li><a href="#indexitem-' + itemindex + '">' + $( this ).text() + '</a></li>' );
			$( '.indexlist a' ).inlineScrolling();
		});
	}
}(jQuery));