public
Created

JavaScript that scrolls down on page load to `<h3>Important</h3>` if you go to `foo.html#Important`

  • Download Gist
scroll-to-headers-in-hash.js
JavaScript
1 2 3 4 5 6 7 8 9 10
// Scroll on page load to the first header where the text matches the hash in the URL
// For example going to 'foo.html#Important' will scroll down to '<h3>Important</h3>'
$(function() {
var h = window.location.hash.replace('#', '')
if ($(h).length)
$('h2,h3,h4,h5,h6').each(function() {
if ($.trim($(this).text().replace(/\s+/g, ' ')) == h)
return window.scrollTo(this.offsetLeft, this.offsetTop)
})
})

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.