Skip to content

Instantly share code, notes, and snippets.

@glueckpress
Created July 31, 2012 15:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save glueckpress/3217725 to your computer and use it in GitHub Desktop.
Save glueckpress/3217725 to your computer and use it in GitHub Desktop.
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));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment