DEATHMETALGORE

Anchor fix

Oct 27th, 2014
274
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function scroll_if_anchor(href) {
  2.     href = typeof(href) == "string" ? href : $(this).attr("href");
  3.  
  4.     // If href missing, ignore
  5.     if(!href) return;
  6.  
  7.     // You could easily calculate this dynamically if you prefer
  8.     var fromTop = 50;
  9.  
  10.     // If our Href points to a valid, non-empty anchor, and is on the same page (e.g. #foo)
  11.     // Legacy jQuery and IE7 may have issues: http://stackoverflow.com/q/1593174
  12.     var $target = $(href);
  13.  
  14.     // Older browsers without pushState might flicker here, as they momentarily
  15.     // jump to the wrong position (IE < 10)
  16.     if($target.length) {
  17.         $('html, body').animate({ scrollTop: $target.offset().top - fromTop });
  18.         if(history && "pushState" in history) {
  19.             history.pushState({}, document.title, window.location.pathname + href);
  20.             return false;
  21.         }
  22.     }
  23. }    
  24.  
  25. // When our page loads, check to see if it contains and anchor
  26. scroll_if_anchor(window.location.hash);
  27.  
  28. // Intercept all anchor clicks
  29. $("body").on("click", "a[href^='#']", scroll_if_anchor);
Advertisement
Add Comment
Please, Sign In to add comment