Maybe you must write <a ... onclick="RemovePicture(); event.stopPropagation();">
.
I have a problem with Javascript: it fires two events simultaneously for a DropZone
I am using a Javascript routine I got online for my MVC Core project, that uses an image drag/drop (like DropZone), and it works very well.
However, I'd like to add an overlay with a trashcan icon, so the user can delete the image if he wants to before submitting.
The script uses an "addEventListener" for a click event, to trigger the <input type=file> element.
I added div and css for the overlay, and attached an "onclick" for the trashcan icon.
My problem is that when a user clicks the trash can, the "onclick" is invoked, but the "addEventListener" also fires at the
same time, so even though the image is removed, the <input> element is fired as well.
Kinda like two click events at the same time.
Is there a way to squelch the addEventListener event when the "onclick" is fired?
Here's a little of my code, to show how I'm using an "onclick" and "addEventListener":
<input type="file" name="myname1" class="dz_input1" id="input1" />
<div class="overlay">
<a href="#" class="icon" title="Remove Picture" onclick="RemovePicture()">
<i class="fa fa-user"></i>
</a>
</div>
<script type="text/javascript">
const inputElement1 = document.getElementById("input1");
const dropzoneElement1 = document.querySelector(".drop-zone1");
dropzoneElement1.addEventListener("click", e => {
inputElement1.click();
});
inputElement1.addEventListener("change", e => {
if (inputElement1.files.length) {
updateThumbnail1(dropzoneElement1, inputElement1.files[0]);
}
});
function updateThumbnail1(dropzoneElement1, file) {
let thumbnailElement = dropzoneElement1.querySelector(".dz_thumb1");
if (dropzoneElement1.querySelector(".user_message")) {
dropzoneElement1.querySelector(".user_message").remove();
}
if (file.type.startsWith("image/")) {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
thumbnailElement.style.backgroundImage = `url('${reader.result}')`;
};
} else {
thumbnailElement.style.backgroundImage = null;
}
}
</script>
Developer technologies ASP.NET ASP.NET Core
-
Viorel 122.5K Reputation points
2023-01-23T20:58:08.9966667+00:00
1 additional answer
Sort by: Most helpful
-
AgaveJoe 30,126 Reputation points
2023-01-23T18:50:18.28+00:00 Events bubble up in JavaScript. You have to stop the event propagation.
<div id="outerElement"> <input type="file" name="myname1" class="dz_input1" id="input1" /> <div class="overlay"> <a href="#" class="icon" title="Remove Picture" onclick="RemovePicture(event)"> <i class="fa fa-user"></i> </a> </div> </div>
Script
<script> $('#outerElement').click(function () { console.log('outerElement fired'); }); function RemovePicture(event) { event.stopPropagation(); console.log('RemovePicture fired'); } </script>