EduardET

Untitled

Mar 16th, 2018
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <script>
  2. ( function( $ ) {
  3.     $( document ).ready( function() {
  4.         function filterPath( string ) {
  5.             return string
  6.                 .replace( /^\//, '' )
  7.                 .replace( /(index|default).[a-zA-Z]{3,4}$/, '' )
  8.                 .replace( /\/$/, '' );
  9.         }
  10.  
  11.         var locationPath = filterPath( location.pathname );
  12.         var scrollElem = scrollableElement( 'html', 'body' );
  13.  
  14.         // Any links with hash tags in them (can't do ^= because of fully qualified URL potential)
  15.         $( 'a[href*=#]' ).each( function() {
  16.  
  17.             // Ensure it's a same-page link
  18.             var thisPath = filterPath( this.pathname ) || locationPath;
  19.             if ( locationPath == thisPath &&
  20.                 ( location.hostname == this.hostname || !this.hostname ) &&
  21.                 this.hash.replace( /#/, '' ) ) {
  22.  
  23.                 // Ensure target exists
  24.                 var $target = $( this.hash ),
  25.                     target = this.hash;
  26.                 if ( target ) {
  27.  
  28.                     // Find location of target
  29.                     var targetOffset = $target.offset().top;
  30.                     $( this ).click( function( event ) {
  31.  
  32.                         // Prevent jump-down
  33.                         event.preventDefault();
  34.  
  35.                         // Animate to target
  36.                         $( scrollElem ).animate( { scrollTop: targetOffset }, 400, function() {
  37.  
  38.                             // Set hash in URL after animation successful
  39.                             location.hash = target;
  40.  
  41.                         } );
  42.                     } );
  43.                 }
  44.             }
  45.  
  46.         } );
  47.  
  48.         // Use the first element that is "scrollable" (cross-browser fix?)
  49.         function scrollableElement( els ) {
  50.             for ( var i = 0, argLength = arguments.length; i < argLength; i++ ) {
  51.                 var el = arguments,
  52.                     $scrollElement = $( el );
  53.                 if ( $scrollElement.scrollTop() > 0 ) {
  54.                     return el;
  55.                 } else {
  56.                     $scrollElement.scrollTop( 1 );
  57.                     var isScrollable = $scrollElement.scrollTop() > 0;
  58.                     $scrollElement.scrollTop( 0 );
  59.                     if ( isScrollable ) {
  60.                         return el;
  61.                     }
  62.                 }
  63.             }
  64.             return [];
  65.         }
  66.     } );
  67. } )( jQuery );
  68. </script>
Advertisement
Add Comment
Please, Sign In to add comment