Search code examples
javascriptjquerysweetalert2

jQuery keydown event not working when sweetalert2 is open


I have a keydown event on my page, however the keydown event is not firing when a sweetalert is open.

$(() => {
    swal.fire({
        icon: "error",
        title: 'Please wait...',
        html: 'Trying again in <b>10</b> seconds.',
        timer: 10000,
        timerProgressBar: true,
        didOpen: () => {
          swal.showLoading()
          timerInterval = setInterval(() => {
            const content = swal.getContent()
            if (content) {
              const b = content.querySelector('b')
              if (b) {
                b.textContent = Math.ceil(swal.getTimerLeft() / 1000);
              }
            }
          }, 1000)
        },
        willClose: () => {
          clearInterval(timerInterval)
        }
      }).then((result) => {
        if (result.dismiss === swal.DismissReason.timer) {
          console.log("finished");
        }
      });
});

$(document).on("keydown", function (e) {
  if (e.key.charCodeAt() == 83 || e.key.charCodeAt() == 115) {
    swal.close();
    console.log("interrupted");
  }
});

See this jsfiddle for an example. While the sweetalert is running, pressing the "S" key is not doing anything, however if you dismiss the sweetalert the keydown triggers.

https://jsfiddle.net/nk087u2s/9/


Solution

  • from the docs

    stopKeydownPropagation: true

    If set to false, SweetAlert2 will allow keydown events propagation to the document.

    $(() => {
      swal.fire({
        stopKeydownPropagation: false,