javascripthtmlcsssweetalert2

how to toggle sweetalert2 themes?


I have a sweetalert2 modal that has a toggle switch for dark mode, and I want to toggle darkmode for the modal.
i tried:

Swal.fire({
            title: 'Settings',
            icon: 'question',
            iconHtml: '<i class="fa fa-cog settings-modal-icon"></i>',
            html: settingsMenuHtml,
            showCloseButton: true,
            showCancelButton: true,
            confirmButtonText: 'Save',
            onOpen: () => {
                document.querySelectorAll('input[type="checkbox"]')[0].checked = Nightly.isDark;
            },
      onBeforeOpen: () => {
        if(Nightly.isDark){
          var ss = document.createElement('link');
          ss.rel = "stylesheet";
          ss.href="//cdn.jsdelivr.net/npm/@sweetalert2/theme-dark@4/dark.css";
          document.head.appendChild(ss);
        }  
      }
})

but this stops the entire page from loading.
how do i fix this??


Solution

  • Please check the Sweetalert2 documentation for willOpen and didOpen which you should use instead of onBeforeOpen and onOpen.

    Apart from that, I set Nightly.isDark to true (for dark mode) and I added some minimal code for settingsMenuHtml, which is necessary to make your modal work.

    In addition, to enable toggling I created a setCSSLink() function which can be called when willOpen is fired and when the settings checkbox is clicked.

    Here is a working code snippet:

    Nightly.isDark = true;
    
    settingsMenuHtml = 
      '<input type="checkbox" onclick="Nightly.isDark = !Nightly.isDark; setCSSLink()">';
    
    Swal.fire({
      title: 'Settings',
      icon: 'question',
      iconHtml: '<i class="fa fa-cog settings-modal-icon"></i>',
      html: settingsMenuHtml,
      showCloseButton: true,
      showCancelButton: true,
      confirmButtonText: 'Save',
      didOpen: () => {
        document.querySelectorAll('input[type="checkbox"]')[0].checked = Nightly.isDark;
      },
      willOpen: () => {
        setCSSLink()
      }
    })
    
    function setCSSLink() {
      var ss = document.createElement('link');
      ss.rel = "stylesheet";
      if (Nightly.isDark) {
        ss.href = "//cdn.jsdelivr.net/npm/@sweetalert2/theme-dark@4/dark.css";
      } else {
        ss.href = "//cdn.jsdelivr.net/npm/@sweetalert2/theme-minimal/minimal.css";
      }
      document.head.appendChild(ss);
    }
    <script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://cdn.jsdelivr.net/gh/fcmam5/nightly.js@v1.0/dist/nightly.min.js"></script>