main.js 1.3 KB

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