main.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /**
  2. * Utils
  3. */
  4. // Throttle
  5. //
  6. const throttle = (callback, limit) => {
  7. let timeoutHandler = null;
  8. return () => {
  9. if (timeoutHandler == null) {
  10. timeoutHandler = setTimeout(() => {
  11. callback();
  12. timeoutHandler = null;
  13. }, limit);
  14. }
  15. }
  16. }
  17. // addEventListener Helper
  18. //
  19. const listen = (ele, e, callback) => {
  20. if (document.querySelector(ele) !== null) {
  21. document.querySelector(ele).addEventListener(e, callback);
  22. }
  23. }
  24. /**
  25. * Functions
  26. */
  27. // Set inner width into CSS variable
  28. //
  29. function setVw() {
  30. let vw = document.documentElement.clientWidth / 100;
  31. document.documentElement.style.setProperty('--vw', `${vw}px`);
  32. }
  33. setVw();
  34. window.addEventListener('resize', setVw);
  35. // ToC toggle
  36. //
  37. function toggleToc() {
  38. const toc = document.getElementById('toc');
  39. if (toc.style.display === 'block') {
  40. toc.style.display = 'none';
  41. } else {
  42. toc.style.display = 'block';
  43. }
  44. }
  45. listen ("#toc-btn", "click", toggleToc);
  46. // Scroll to Top
  47. //
  48. const scrollBtn = document.getElementById('scroll-top-btn');
  49. const btnVisibility = () => {
  50. if ((window.scrollY > 400) && (window.innerWidth >= 1530)) {
  51. scrollBtn.style.display = "block";
  52. } else {
  53. scrollBtn.style.display = "none";
  54. }
  55. };
  56. if (scrollBtn !== null) {
  57. scrollBtn.addEventListener("click", () => {
  58. window.scrollTo(0,0);
  59. });
  60. }
  61. // Anchor points for list page
  62. //
  63. document.querySelectorAll('.post-year').forEach((ele)=> {
  64. ele.addEventListener('click', () => {
  65. window.location.hash = '#' + ele.id;
  66. });
  67. });
  68. window.addEventListener('scroll', throttle(() => {
  69. if (scrollBtn !== null) {
  70. btnVisibility();
  71. }
  72. }, 150));