I want to enhance the user experience of my web app by making elements fade away before being removed. However, I am facing an issue where my code is executing too quickly. I need it to wait for the element to "disappear" before actually removing it. Should I use a Promise
or setTimeout()
in this scenario?
Code Overview
Check if variables exist
If button is clicked, change element opacity (transition: opacity 1s;)
Then call deletePostPromise()
Finally, remove the element from the DOM
As you can see, even my pseudocode is written as a promise with then.. then..
.
Specifically, we start at row.style.opacity = '0';
If (displayPostWrapper && submitPostBtn) {
displayPostWrapper.addEventListener('click', e => {
If (e.target && e.target.nodeName == 'BUTTON') {
e.preventDefault();
const { parentElement } = e.target;
const row = parentElement.parentElement.parentElement;
const form = parentElement;
const postID = parentElement.childNodes[3].value;;
row.style.opacity = '0';
deletePostPromise('http://localhost/mouthblog/ajax/delete_post.ajax.php', `id=${postID}`)
.then(() => {
row.remove();
});
// row.remove();
} // If
}); // click event
EDIT
JS
const deletePostPromise = (url, postID) => {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.onload = () => {
If (xhr.status == 200) {
console.log('if (xhr.status == 200)');
resolve();
} Else {
reject(xhr.statusText);
}
};
xhr.onerror = () => {
reject(xhr.statusText);
};
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send(postID);
});
}
If (displayPostWrapper && submitPostBtn) {
displayPostWrapper.addEventListener('click', e => {
If (e.target && e.target.nodeName == 'BUTTON') {
e.preventDefault();
const { parentElement } = e.target;
const row = parentElement.parentElement.parentElement;
const form = parentElement;
const postID = parentElement.childNodes[3].value;;
row.style.opacity = '0';
deletePostPromise('http://localhost/mouthblog/ajax/delete_post.ajax.php', `id=${postID}`);
row.addEventListener("transitionend", function(event) {
// alert('Done!');
row.remove();
}, false);
} // If
}); // click event
CSS
.row {
opacity: 1;
transition: opacity 5s;
}