rakeshr

jQuwey smooth scrolling

May 5th, 2018
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
jQuery 1.23 KB | None | 0 0
  1. // Select all links with hashes
  2. jQuery('a[href*="#"]')
  3.   // Remove links that don't actually link to anything
  4.   .not('[href="#"]')
  5.   .not('[href="#0"]')
  6.   .click(function(event) {
  7.     // On-page links
  8.     if (
  9.       location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
  10.       &&
  11.       location.hostname == this.hostname
  12.     ) {
  13.       // Figure out element to scroll to
  14.       var target = jQuery(this.hash);
  15.       target = target.length ? target : jQuery('[name=' + this.hash.slice(1) + ']');
  16.       // Does a scroll target exist?
  17.       if (target.length) {
  18.         // Only prevent default if animation is actually gonna happen
  19.         event.preventDefault();
  20.         jQuery('html, body').animate({
  21.           scrollTop: target.offset().top
  22.         }, 1000, function() {
  23.           // Callback after animation
  24.           // Must change focus!
  25.           var $target = jQuery(target);
  26.           $target.focus();
  27.           if ($target.is(":focus")) { // Checking if the target was focused
  28.             return false;
  29.           } else {
  30.             $target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
  31.             $target.focus(); // Set focus again
  32.           };
  33.         });
  34.       }
  35.     }
  36.   });
Add Comment
Please, Sign In to add comment