Skip to content

Instantly share code, notes, and snippets.

@ed-codes
Created April 12, 2017 03:22
Show Gist options
  • Save ed-codes/dc9469e2d98f340a4f1c0b3e6d37db69 to your computer and use it in GitHub Desktop.
Save ed-codes/dc9469e2d98f340a4f1c0b3e6d37db69 to your computer and use it in GitHub Desktop.
used in Shopify - create index at top of a static page from heading tags, scroll to headings.
jQuery(function() {
var $headings = jQuery('.page-content').find('h2,h4');
var $anchor_list = jQuery('<ul class="anchor-list"></ul>');
var idx = 1;
var $list_item;
$headings.each(function() {
jQuery(this).prepend('<a id="link-' + idx + '"></a>');
$list_item = jQuery('<li></li>');
if (jQuery(this).prop("tagName") == 'H4') {
$list_item.addClass('sub-item');
}
$list_item.html('<a href="#link-' + idx + '">' + jQuery(this).text() + '</a>');
$anchor_list.append($list_item);
idx++;
});
$anchor_list.find('a').on('click', function() {
var link_id = $(this).attr('href');
var $anchor = jQuery(link_id);
if ($anchor.length) {
jQuery('html, body').animate({
scrollTop: $anchor.offset().top - 70
}, 1000);
return false;
}
});
jQuery('.page-content').prepend($anchor_list);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment