bookmark.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /* global CONFIG */
  2. window.addEventListener('DOMContentLoaded', () => {
  3. 'use strict';
  4. var doSaveScroll = () => {
  5. localStorage.setItem('bookmark' + location.pathname, window.scrollY);
  6. };
  7. var scrollToMark = () => {
  8. var top = localStorage.getItem('bookmark' + location.pathname);
  9. top = parseInt(top, 10);
  10. // If the page opens with a specific hash, just jump out
  11. if (!isNaN(top) && location.hash === '') {
  12. // Auto scroll to the position
  13. window.anime({
  14. targets : document.scrollingElement,
  15. duration : 200,
  16. easing : 'linear',
  17. scrollTop: top
  18. });
  19. }
  20. };
  21. // Register everything
  22. var init = function(trigger) {
  23. // Create a link element
  24. var link = document.querySelector('.book-mark-link');
  25. // Scroll event
  26. window.addEventListener('scroll', () => link.classList.toggle('book-mark-link-fixed', window.scrollY === 0));
  27. // Register beforeunload event when the trigger is auto
  28. if (trigger === 'auto') {
  29. // Register beforeunload event
  30. window.addEventListener('beforeunload', doSaveScroll);
  31. window.addEventListener('pjax:send', doSaveScroll);
  32. }
  33. // Save the position by clicking the icon
  34. link.addEventListener('click', () => {
  35. doSaveScroll();
  36. window.anime({
  37. targets : link,
  38. duration: 200,
  39. easing : 'linear',
  40. top : -30,
  41. complete: () => {
  42. setTimeout(() => {
  43. link.style.top = '';
  44. }, 400);
  45. }
  46. });
  47. });
  48. scrollToMark();
  49. window.addEventListener('pjax:success', scrollToMark);
  50. };
  51. init(CONFIG.bookmark.save);
  52. });