Created
April 12, 2017 03:22
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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