From 04ccdf6f762475b3b70d4512016790ae87789696 Mon Sep 17 00:00:00 2001 From: Omar Ahmed Hassan <98468609+omar-ahmed42@users.noreply.github.com> Date: Mon, 2 Dec 2024 19:41:11 +0200 Subject: [PATCH] Fix: prevent fileInput.js from adding event listeners more than once (#2365) Fix fileInput.js adding event listeners more than once - Fix a bug that caused fileInput.js to add event listeners more than once per HTML file as it's included in fileSelector fragment in fragments/common.html thus it's being loaded N times where N is the number of file selectors / custom file chooser / file input elements per HTML file, which resulted in each event actions being executed N times as well, which was prevalent in drag and drop operations such as dragging and dropping a file called y.png, it would be duplicated N times (as in /sign path). --- src/main/resources/static/js/fileInput.js | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/main/resources/static/js/fileInput.js b/src/main/resources/static/js/fileInput.js index 103226f3aba..4b0cdd33da3 100644 --- a/src/main/resources/static/js/fileInput.js +++ b/src/main/resources/static/js/fileInput.js @@ -1,6 +1,10 @@ -document.addEventListener("DOMContentLoaded", function () { - document.querySelectorAll(".custom-file-chooser").forEach(setupFileInput); -}); +let isScriptExecuted = false; +if (!isScriptExecuted) { + isScriptExecuted = true; + document.addEventListener("DOMContentLoaded", function () { + document.querySelectorAll(".custom-file-chooser").forEach(setupFileInput); + }); +} function setupFileInput(chooser) { const elementId = chooser.getAttribute("data-bs-element-id"); @@ -85,7 +89,7 @@ function setupFileInput(chooser) { $("#" + elementId).on("change", function (e) { let element = e.target; const isDragAndDrop = e.detail?.source == 'drag-drop'; - + if (element instanceof HTMLInputElement && element.hasAttribute("multiple")) { allFiles = isDragAndDrop ? allFiles : [... allFiles, ... element.files]; } else {