Skip to content

Instantly share code, notes, and snippets.

@glueckpress
Last active April 28, 2019 12:23
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save glueckpress/06f0ba19ae1d17b4789c to your computer and use it in GitHub Desktop.
Save glueckpress/06f0ba19ae1d17b4789c to your computer and use it in GitHub Desktop.
[JavaScript][jQuery] Inline Anchor Navigation: Adds a smooth scroll effect to URLs containing a hash (#). Excludes single hashes, #respond (WordPress comment forms), and orphaned hash characters at the end of a URL.
/**
* jQuery Inline Anchor Navigation
*
* Adds a smooth scroll effect to URLs containing a hash (#).
* Excludes single hashes, #respond (WordPress comment forms), and orphaned
* hash characters at the end of a URL.
*/
(function($) {
$('a[href*="#"]')
.not('a[href="#"]') // Excemption #1: dummy hrefs
.not('a[href*="#respond"]') // Excemption #2: WordPress comment form
.on('click.achornav', function(e) {
var linktHref = this.href.split('#');
if(linktHref[1] === '') { // Excemption #3: orphaned # at end of URL
e.preventDefault();
return false;
}
var currentUrlRoot = window.location.href.split('#')[0],
scrollToAnchor = $('#' + linktHref[1]).offset().top;
// Animate for targets on the same page.
if(linktHref[0] === currentUrlRoot) {
$('html, body')
.animate({ scrollTop : scrollToAnchor }, 250 ); // Duration: 250ms.
e.preventDefault();
return false;
} else {
// For targets on other pages, just go to URL.
window.location.href = this.href;
}
return false;
});
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment