briank

Smooth Scroll To Anchor

May 27th, 2022 (edited)
294
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 0.68 KB | None | 0 0
  1. <script>
  2. /* Code from Anthony Hull with revisions by Brian Katzung */
  3. jQuery('body').on('click', 'a[href*="#"]', function (ev) {
  4.     /*
  5.      * When clicking on a same-page hash...
  6.      * (considering host+port+path match as same page)
  7.      */
  8.     if (this.host === location.host && this.pathname === location.pathname) {
  9.     var hash = this.hash;
  10.         ev.preventDefault(); // Prevent default click action (jump scroll)
  11.         jQuery('html, body').animate({ // (Smooth scroll)
  12.             scrollTop: jQuery(hash).offset().top
  13.           }, 800 /* milliseconds */, function () {
  14.             location.hash = hash; // Normalize URL upon arrival
  15.         });
  16.     }
  17. });
  18. </script>
Add Comment
Please, Sign In to add comment