Is it time to consider using a Promise in my JavaScript code given its rapid pace of execution?

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;
    }

Answer №1

To detect when the opacity transition is complete, set a listener using the transitionend event. This listener will notify you when the transition has finished, allowing you to remove the element.

row.addEventListener("transitionend", function(event) {
  console.log("Transition completed, removing row");
  row.remove();
}, false);

Add this listener just before changing the opacity to initiate the fadeout.

Take a look at this simple example to observe it in action:

function log(msg) {
    let div = document.createElement("div");
    div.innerHTML = msg;
    document.getElementById("log").appendChild(div);
}

document.getElementById("run").addEventListener("click", function() {
    document.getElementById("test").style.opacity = 0;
});

let test = document.getElementById("test");

test.addEventListener("transitionend", function(e) {
    log(`transitionend for ${e.propertyName}, removing DOM element`)
    test.remove();
});
.fade {
   opacity: 1;
   transition: opacity 2s;
}
<button id="run">
Start Animation
</button>
<div class="fade" id="test">
Some content that will fade out
</div>
<div id="log">

</div>
"

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When getStaticPaths and getStaticProps are programmed to deliver results

Seeking assistance with my first attempt at using getStaticPaths and getStaticProps in nextJS as a beginner. Can anyone help me resolve this issue? const datas = [ { id: 1, name: "Banheiro", image: "https://res.cl ...

The repeated execution of a Switch Statement

Once again, I find myself facing a puzzling problem... Despite making progress in my game, revisiting one aspect reveals a quirk. There's a check to verify if the player possesses potions, and if so, attempts to use it involves calculating whether the ...

Locate identical values within an array in MongoDB, even if they exist independently of an object

{ "_id" : ObjectId("15672"), "userName" : "4567", "library" : [ { "serialNumber" : "Book_1" }, { "serialNumber" : "Book_2" }, { "serialNumber" : "Book_4" } ...

Leveraging Vue properties within CSS styling

I am looking to utilize Vue data/prop variables within the <style> tag located at the bottom of my component. For example, suppose I have a component structured like this: <template> <div class="cl"></div> </template> < ...

I have been working on incorporating a menu item in React, but I keep encountering an error

I am using the MenuItem component to create a dropdown menu in my React project. Despite importing the necessary package, I am encountering an error when running the server. I have searched for solutions but haven't found a definitive me ...

Rearrange div elements following an ajax request based on a data attribute and applying the .animate method

I am dealing with a collection of div elements, each assigned a unique numeric id and data-position in sequential order (1 for the first in the list, 2 for the second, and so on). Upon making an ajax call using jQuery, the response is a JSON object that r ...

Steps to extract a hash from a document's URL

The following code is used: jQuery(document).ready(function() { console.log($(this)); }); After running this code, the object displayed in the console is: [Document mypage.html#weather] How can I retrieve the last ID from this object? In this ...

What is the best way to monitor a variable using the controllerAs syntax in Angular?

When utilizing the standard controller syntax in AngularJS, you have the ability to watch a variable with code like this: $scope.$watch(somethingToWatch, function() { alert('It changed!'); }); However, with the controllerAs syntax, how can I ea ...

Updating multiple collections in MongoDBRestructuring data across multiple

Imagine a scenario where an API call must update two different collections. It's crucial that if one update fails, the first update needs to be reverted. How can I guarantee that both operations either complete successfully or none at all? Let me prov ...

The powerful combination of ES6 and sequelize-cli

How can I execute sequelize migrations and seeds written in ES6? I attempted to use babel-node, but encountered a strange error. Command node_modules/babel-cli/lib/babel-node.js node_modules/sequelize-cli/bin/sequelize db:seed Error node_modules/b ...

Incorporating a transparent icon onto an HTML background

I'm struggling to place a transparent white envelope icon on a green background. I don't understand why it's not working, especially when the telephone icon worked fine. Side Question.: Any recommendations for how to add something above the ...

Loop through a collection of unique identifiers for documents and establish event listeners in Firestore

Within my Vuex store, there is an action designed to retrieve a list of uids for followed users from the current user's Firestore UserDataCollection document. The action then processes each uid to extract data that will be displayed on the UI. While t ...

Updating the button text in Angular 7

Here's a question: <button (click)="activateMotion(1)"> <img class="emotion-icon" id="positive-icon" src="" /> </button> <button (click)="activateMotion(-1)"> <img class="emotion-icon" id="negative-icon" src="" /&g ...

Unlock the potential of accessing data from the parent controller within a child controller in AngularJS

Is it possible to retrieve model data from the parent controller within a child controller? <div ng-controller="abc"> <div ng-controller="def"> <span> {{name}}</span> </div> </div> Can we access the val ...

Is there a solution to rectify the error related to POST net::ERR_CONNECTION_REFUSED?

Every time I try to post via ajax, an error keeps popping up. Here are the snippets of my code: let xhr = new XMLHttpRequest() let data ={ "name": "test", "phone": "12345678", "email": &qu ...

Can you explain the distinction between a synchronous and asynchronous request in terms of their async parameter values (true/false)?

Can you explain the difference between setting async=false and async=true when utilizing the open method of the XMLHttpRequest? function GetXML() { if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new X ...

Is it possible to perform ECDH Key Exchange using public keys of varying lengths?

Currently, I am working on implementing an ECDH key-exchange using the P-384 curve. While other curves could be used, I believe the implementations should be fairly similar in nature. The goal is for the Client (Javascript) and Server(Java) to establish a ...

extract information from local storage using AngularJS

I'm having trouble getting the filter to work in my AngularJS project with local storage. Even though there are no errors, nothing happens when I type words into the input field. Can someone lend a hand? :) html: <div ng-app="myApp" ng-controller ...

Exploring object properties within arrays and nested objects using ReactJS

Within the react component PokemonInfo, I am looking to extract the stats.base_stat value from the JSON obtained from https://pokeapi.co/api/v2/pokemon/1/. The issue lies in the fact that base_stat is nested inside an array called stats. My assumption is t ...

How come my express POST endpoint delivers a 404 error when the Content-Type is specified by the requester?

My express server configuration is: import express from "express"; const app = express() const port = 3000; app.use(express.json()) app.use((req, res, next) => { res.header("Access-Control-Allow-Origin", "*"); res.h ...