mine.js 1.8 KB

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