Good day everyone.
So I’m getting my “works” from an API ( http…/api/works ). I have all the works displayed on my main page using fetch method get, but also on a modal that opens up when I click a “modify” button. My modal appears with all the images and a “delete” button on each image so I can delete them from the API/DOM. My problem is that when I click that button :
1: the page reloads ( I do not wish for that to happen )
2: the image is deleted from the main page and the modal and also the API. ( which is what I wish for ).
This is the code I use :
const showModal = document.getElementById("showModal");
showModal.addEventListener("click", async (event) => {
event.preventDefault();
// check if user is connected
const token = localStorage.getItem("token");
const articles = await fetchData("http://localhost:5678/api/works", {
headers: { Authorization: `Bearer ${token}` },
});
const modalContentImg = document.querySelector(".modalContentBody");
// Refresh modal body to not have duplicates everytime we open the modal
modalContentImg.innerHTML = "";
// Find the first article in the array
const firstArticle = articles[0];
articles.forEach((article, index) => {
const projectArticle = document.createElement("article");
projectArticle.classList.add("articleWrapper");
const img = document.createElement("img");
img.setAttribute("src", article.imageUrl);
img.setAttribute("data-id", article.id);
img.classList.add("modalImg");
const deleteBtn = document.createElement("button");
deleteBtn.innerHTML = '<i class="fas fa-trash-can"></i>';
deleteBtn.classList.add("deleteImage");
const edit = document.createElement("p");
edit.textContent = "éditer";
// Add another button only to the first image
if (article.id === firstArticle.id && index === 0) {
const moveBtn = document.createElement("button");
moveBtn.innerHTML = '<i class="fa-solid fa-up-down-left-right"></i>';
moveBtn.classList.add("moveBtn");
projectArticle.appendChild(moveBtn);
}
// Delete image from API when button is clicked
deleteBtn.addEventListener("click", async (e) => {
e.preventDefault();
const token = localStorage.getItem("token");
await fetchData(`http://localhost:5678/api/works/${article.id}`, {
method: "DELETE",
headers: {
Authorization: `Bearer ${token}`,
},
});
projectArticle.remove();
// Delete Image from the main page using the id
const mainImg = document.querySelector(`[data-id="${article.id}"]`);
if (mainImg) {
mainImg.parentNode.remove();
}
});
modalContentImg.appendChild(projectArticle);
projectArticle.appendChild(img);
projectArticle.appendChild(deleteBtn);
projectArticle.appendChild(edit);
});
document.getElementById("modal").classList.add("visible");
});