skip to Main Content

I have a dialog to show to user an input type file. I have an issue when the user canceled the input file or when he chooses the same file, that closes my dialog. I don’t want that, so I added event Listener ‘cancel’ with event prevent default. But that didn’t work.

<button id="openDialogButton">Open dialog</button>

<dialog id="dialog">
  <h1>Hi, I'm a dialog !</h1>

  <input type='file'>

  <p><button id="closeDialogButton">Close dialog</button></p>
</dialog>
const buttonOpen = document.querySelector("#openDialogButton");
const buttonClose = document.querySelector("#closeDialogButton");
const dialog = document.querySelector("#dialog");

buttonOpen.addEventListener("click", (e) => {
  dialog.showModal();
});

buttonClose.addEventListener("click", (e) => {
  dialog.close();
});

dialog.addEventListener("cancel", (e) => {
  console.log(e);
  e.preventDefault();
});

codepen here : https://codepen.io/catif/pen/LYgKNmN

2

Answers


  1. Chosen as BEST ANSWER

    After the comment of Simone Rossaini, I tried on Firefox, Edge, Opera and Chrome.

    All Chromium's browsers didn't work, and that already a bug reported on Chromium => https://bugs.chromium.org/p/chromium/issues/detail?id=1449848


  2. It seems that preventing the dialog from closing when you cancels/add same file selection is not directly achievable with the current dialog implementation.
    One alternative solution is to create a custom dialog using HTML and CSS, and handle the file selection logic manually.

    const buttonOpen = document.querySelector("#openDialogButton");
    const buttonClose = document.querySelector("#closeDialogButton");
    const dialog = document.querySelector("#customDialog");
    const fileInput = document.querySelector("#fileInput");
    
    buttonOpen.addEventListener("click", () => {
      dialog.style.display = "block";
    });
    
    buttonClose.addEventListener("click", () => {
      dialog.style.display = "none";
    });
    
    fileInput.addEventListener("change", (e) => {
      const selectedFile = e.target.files[0];
      if (!selectedFile) {
        return; // Ignore if no file is selected
      }
    
      // Handle the selected file here
      console.log("Selected file:", selectedFile);
    });
    .custom-dialog {
      position: fixed;
      top: 50%;
      left: 50%;
      background-color: white;
      padding: 20px;
      display: none;
    }
    <button id="openDialogButton">Open dialog</button>
    
    <div id="customDialog" class="custom-dialog">
      <h1>Hi, I'm a dialog!</h1>
    
      <input type="file" id="fileInput">
    
      <p><button id="closeDialogButton">Close dialog</button></p>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search