mine.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. var $window = $(window);
  2. var hash = window.location.hash;
  3. window.location.hash = ''; // avoid going to anchor
  4. $window.on('load', function() {
  5. var content = $('#content');
  6. var size = 24; // magic number !
  7. // nav is not displayed on small screens so no need to continue
  8. if (window.matchMedia('(max-width: 40rem)').matches) {
  9. return;
  10. }
  11. content.find('h2:last').add('h2:last ~ *').each(function() {
  12. size += $(this).outerHeight(true);
  13. });
  14. content.css('margin-bottom', $window.height() - size);
  15. $('#toc').sticky({topSpacing:30});
  16. var navs = $('#side-nav ul li a');
  17. var navItemsMap = {};
  18. var navItems = navs.map(function(_, item) {
  19. var anchor = item.getAttribute('href');
  20. var anchorItem = $(anchor);
  21. var navItem = {
  22. 'nav': $(item),
  23. 'anchor': {'name': anchor, 'item': anchorItem},
  24. 'pos': anchorItem.offset().top
  25. };
  26. navItemsMap[anchor] = navItem;
  27. return navItem;
  28. });
  29. $window.scroll(function(){
  30. var nav;
  31. var pos = $window.scrollTop();
  32. $.each(navItems, function(_, item) {
  33. return pos > item.pos - 1 ? nav = item.nav : false;
  34. });
  35. if (nav) {
  36. navs.removeClass('active');
  37. nav.addClass('active');
  38. }
  39. });
  40. if (hash) {
  41. goTo(hash);
  42. } else {
  43. navs.first().addClass('active');
  44. }
  45. navs.on('click',function(e){
  46. e.preventDefault();
  47. goTo(e.currentTarget.getAttribute('href'));
  48. });
  49. function goTo(hash) {
  50. $('body,html').animate(
  51. {scrollTop: navItemsMap[hash].pos}, 1000, 'swing',
  52. function() {
  53. window.location.hash = hash;
  54. }
  55. );
  56. }
  57. $('.burger').on('click',function(){
  58. $('#banner nav').toggleClass('opened');
  59. $('.cacheMenu').fadeToggle();
  60. });
  61. $('.cacheMenu').on('click',function(){
  62. $('#banner nav').toggleClass('opened');
  63. $('.cacheMenu').fadeToggle();
  64. });
  65. });