Sin descripción

dark-mode-toggler.js 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. function toggleDarkMode() { // jshint ignore:line
  2. var toggler = document.getElementById( 'dark-mode-toggler' );
  3. if ( 'false' === toggler.getAttribute( 'aria-pressed' ) ) {
  4. toggler.setAttribute( 'aria-pressed', 'true' );
  5. document.documentElement.classList.add( 'is-dark-theme' );
  6. document.body.classList.add( 'is-dark-theme' );
  7. window.localStorage.setItem( 'twentytwentyoneDarkMode', 'yes' );
  8. } else {
  9. toggler.setAttribute( 'aria-pressed', 'false' );
  10. document.documentElement.classList.remove( 'is-dark-theme' );
  11. document.body.classList.remove( 'is-dark-theme' );
  12. window.localStorage.setItem( 'twentytwentyoneDarkMode', 'no' );
  13. }
  14. }
  15. function twentytwentyoneIsDarkMode() {
  16. var isDarkMode = window.matchMedia( '(prefers-color-scheme: dark)' ).matches;
  17. if ( 'yes' === window.localStorage.getItem( 'twentytwentyoneDarkMode' ) ) {
  18. isDarkMode = true;
  19. } else if ( 'no' === window.localStorage.getItem( 'twentytwentyoneDarkMode' ) ) {
  20. isDarkMode = false;
  21. }
  22. return isDarkMode;
  23. }
  24. function darkModeInitialLoad() {
  25. var toggler = document.getElementById( 'dark-mode-toggler' ),
  26. isDarkMode = twentytwentyoneIsDarkMode();
  27. if ( isDarkMode ) {
  28. document.documentElement.classList.add( 'is-dark-theme' );
  29. document.body.classList.add( 'is-dark-theme' );
  30. } else {
  31. document.documentElement.classList.remove( 'is-dark-theme' );
  32. document.body.classList.remove( 'is-dark-theme' );
  33. }
  34. if ( toggler && isDarkMode ) {
  35. toggler.setAttribute( 'aria-pressed', 'true' );
  36. }
  37. }
  38. function darkModeRepositionTogglerOnScroll() {
  39. var toggler = document.getElementById( 'dark-mode-toggler' ),
  40. prevScroll = window.scrollY || document.documentElement.scrollTop,
  41. currentScroll,
  42. checkScroll = function() {
  43. currentScroll = window.scrollY || document.documentElement.scrollTop;
  44. if (
  45. currentScroll + ( window.innerHeight * 1.5 ) > document.body.clientHeight ||
  46. currentScroll < prevScroll
  47. ) {
  48. toggler.classList.remove( 'hide' );
  49. } else if ( currentScroll > prevScroll && 250 < currentScroll ) {
  50. toggler.classList.add( 'hide' );
  51. }
  52. prevScroll = currentScroll;
  53. };
  54. if ( toggler ) {
  55. window.addEventListener( 'scroll', checkScroll );
  56. }
  57. }
  58. darkModeInitialLoad();
  59. darkModeRepositionTogglerOnScroll();