Incorporate CSS animations prior to removing an element from an array

Before removing an item from my data table, I want to implement a CSS animation. The deletion is initiated by the @click event. I would like to preview the effect of my animation (class delete_animation) before proceeding with the actual removal.

var vm = new Vue({
  el: '#app',
  data: {
    addedId: null,
    array: [
      { id: 1, text: "lorem ipsum" },
      { id: 2, text: "lorem ipsum" },
    ]
  },
  methods: {
    add() {
      this.addedId = this.array[this.array.length - 1].id + 1;
      this.array.push({ id: this.addedId, text: "lorem ipsum"} );
    },
    remove(item, index) {
      this.array.splice(index, 1);
      this.addedId = null;
      // ???
    }
  }
});
table {
    border-collapse: collapse;
}

table, th, td {
    border: 1px solid black;
}

.add_animation {
  animation: addItem 1s;
}

@keyframes addItem {
  0% {
    background-color: green;
  }
  100% {
    background-color: white;
  }
}
.deleted_animation {
  animation: deleteItem 1s;
}
@keyframes deleteItem {
  0% {
    background-color: red;
  }
  100% {
    background-color: white;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.11/vue.min.js"></script>
<div id="app">
  <table>
    <tr v-for="(index, item) in array" :key="item.id" :class="addedId == item.id ? 'add_animation' : ''">
      <td>{{ item.text }}</td>
      <td> <button type="button" @click="remove(item, index)">remove</button></td>
    </tr>
  </table>
  <button type="button" @click="add()">Add</button>
</div>

I'm looking to reverse the action of the "add" button using events that wait for the animation to complete. Possibly triggering a click once the animation has been displayed, but not quite sure how to achieve this...

Thank you!

Answer №1

It seems like you're interested in animating the deletion of an item in an array using vue.js.

Vue.js makes it easy to accomplish this, so be sure to check out Vue.js Transitions

I've put together a simple example for you that showcases how items can be animated when deleted. Hopefully, it will be helpful to you.

See the animation in action here

The "html" section

<div id="app">
  <transition-group name="fade">
      <div v-for="(todo,index) in todos" :key="todo.text" @click="deleteItem(index)">
        {{ todo.text}}
      </div>
  </transition-group>
</div>

The javascript portion

new Vue({
  el: "#app",
  data: {
    todos: [
      { text: "Learn JavaScript", done: false },
      { text: "Learn Vue", done: false },
      { text: "Play around in JSFiddle", done: true },
      { text: "Build something awesome", done: true }
    ]
  },
  methods: {
        deleteItem(index) {
        this.todos.splice(index, 1);
    }
  }
})

The css component

.fade-leave-active {
  transition: all 1s;
}

.fade-leave-to {
  opacity: 0;
}

Answer №2

To enhance your list with smooth transitions, wrap it in a <transition-group> element. By defining your transitions as CSS transitions, Vue.js will automatically handle the necessary CSS classes to maintain the element while the exit transition is in progress. You won't need to alter your code logic at all. For more detailed instructions, refer to the "List Transitions" section in the documentation.

https://v2.vuejs.org/v2/guide/transitions.html#List-Transitions

Answer №3

To start, if you apply the deletedItem class to the item that was clicked:

document.querySelectorAll('tr')[index].classList.add('deleted_animation')

(There may be a more efficient way to target the clicked item)

Next, use setTimeout to create a delay before taking action:

setTimeout(() => {
    this.array.splice(index, 1);
    this.addedId = null;
}, 500)

This method should work effectively. However, relying on indexes may not be ideal as it could lead to multiple rapid clicks on the remove button. To mitigate this, consider disabling all buttons temporarily after one is clicked, and then re-enabling them once the item has been removed.

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

Is there a way to update my profile picture without having to constantly refresh the page after uploading it?

Here is the code for my profile page. I am considering using a callback along with another useEffect function, but I'm unsure. Please help me in finding a solution. For now, let's ignore all the code related to deleting, saving, and handling ingr ...

An easy way to enable mobility for BootstrapDialog on mobile devices

Currently, I am utilizing the library available at https://github.com/nakupanda/bootstrap3-dialog in order to create a dialog box. However, my issue arises when viewing the dialog on mobile devices where it exceeds the screen size. On desktops, adjusting t ...

Choosing bookmarkable views in Angular 5 without using routes

I'm currently working on a unique Angular 5 application that deviates from the standard use of routes. Instead, we have our own custom menu structure for selecting views. However, we still want to be able to provide bookmarkable URLs that open specifi ...

Simulated function invocation just one time

I am testing the functionality of two functions in the same file. One of the functions is supposed to call the other, and I need to verify that this interaction occurs. import * as strings from './strings'; const generateUuidSpy = jest.spyOn(st ...

Is it advisable to send a response in Express.js or not?

When working with Express.js 4.x, I'm unsure whether to return the response (or next function) or not. So, which is preferred: Option A: app.get('/url', (req, res) => { res.send(200, { message: 'ok' }); }); Or Option B: ...

Failed to insert a new element into the MongoDB array

After trying the code below to update a document within a collection, I encountered an issue where a new item was not being added to an array in the script. Despite no exceptions being thrown, the array remained unchanged. I am seeking advice from experts ...

Generating a list of objects from an array of strings

I am currently facing an issue in my code and I could use some help with it. Below are the details: I have a array of string values containing MAC addresses and constant min & max values. My goal is to map over these MAC values and create an array of obje ...

Is it possible for JavaScript to style two different phone number elements on a single page?

After successfully creating a script that auto formats an element by ID on my website, I encountered an issue with multiple forms. The script works perfectly for a single element, but when I attempted to change it to target elements by class name using get ...

Looking to update the key name in a script that produces a list sorted in ascending order

I have been working on code that iterates through a flat json document and organizes the items into a hierarchical structure based on their level and position. Everything is functioning correctly, but I now need to change the name of the child elements to ...

Testing NestJS Global ModulesExplore how to efficiently use NestJS global

Is it possible to seamlessly include all @Global modules into a TestModule without the need to manually import them like in the main application? Until now, I've had to remember to add each global module to the list of imports for my test: await Tes ...

Can someone explain the inner workings of the Typescript property decorator?

I was recently exploring Typescript property decorators, and I encountered some unexpected behavior in the following code: function dec(hasRole: boolean) { return function (target: any, propertyName: string) { let val = target[propertyName]; ...

Transferring environment variables from Azure pipelines to a Vue application using Quasar 2.6 with a readonlyrootfilesystem configuration

I am currently working on a Vue App that is powered by Quasar 2.6. I recently made a configuration change in my AWS task definition to set readonlyrootfilesystem to true. However, I encountered a problem when trying to write environment variables to a file ...

"Learn how to trigger an event from a component loop up to the main parent in Angular 5

I have created the following code to loop through components and display their children: parent.component.ts tree = [ { id: 1, name: 'test 1' }, { id: 2, name: 'test 2', children: [ { ...

Utilizing the Twitter API variable within ExpressJS while incorporating AngularJS

Using the "twit" Twitter package from GitHub, I am able to call the Twitter API and retrieve data that is logged in the console. However, I am unsure of how to pass this data to AngularJS in order to display the tweets on the front-end. T.get('search ...

Identifying HTTP Live Streaming on mobile devices

I am seeking a reliable method to determine if a mobile device can play HTTP Live Streaming (m3u8). Currently, I am using the following script for testing purposes: function isHLSEnabled() { var videoElement = document.createElement('video' ...

Exploring methods to verify a service subscription to a topic provided by a different service

My services provide the following functionalities: @Injectable({ providedIn: 'root' }) export class Service1 { dataHasChanged = new Subject(); private data1; private data2; constructor() {} getData() { return { data1: th ...

Guide on implementing themes to HTML within the append() function

I am currently working on a project where I need to dynamically add HTML tags using JavaScript. However, I have noticed that the themes or styles are not being applied to the newly added elements within the append method. In my HTML file, I am using jQue ...

Establishing express routing results in API call returning 404 error indicating resource not found

I need some clarification on how to configure my Express routing using app.use and router. My understanding is that I can create a router and then attach it to a route using app.use() to handle all routing related to that route. Can someone assist me in ...

Is there a reason why the Chrome browser doesn't trigger a popstate event when using the back

JavaScript: $(document).ready(function() { window.history.replaceState({some JSON}, "tittle", aHref); $(window).bind("popstate", function(){ alert("hello~"); }); }); Upon the initial loading of the www.example.com page, the above JavaScript code is ex ...

Undefined is the value assigned to Javascript Dot Notation

When using dot notation to access objects with a '.', I am encountering an issue that I cannot seem to figure out. The success function in my jQuery $.ajax function looks like this: success: function(data){ console.log('data = ' + da ...