CSS Animation on Element Removal

by mithril

Level: beginner • Mithril.js Version: latest

This is an example using CSS animation on element removal. The difficulty here is that we must wait until the animation is complete before we can actually remove the element. Therefore Mithril.js offers the onbeforeremove hook that allows us to defer the removal of an element. This example was taken from the official website at https://mithril.js.org/animation.html#animation-on-element-removal and slightly modified.

Live Example

Dependencies

Type Name URL
scriptmithril@latesthttps://unpkg.com/mithril@latest

Styles

.fancy {
  font-size: 2rem;
}
.exit {
  animation:fade-out 2.0s;
  font-size: 2rem;
}
@keyframes fade-out {
  from {opacity:1;}
  to {opacity:0;}
}

JavaScript

var on = true

var Toggler = {
  view: function() {
    return [
      m("button", {onclick: function() {on = !on}}, "Toggle"),
      on ? m(FancyComponent) : null,
    ]
  }
}

var FancyComponent = {
  onbeforeremove: function(vnode) {
    vnode.dom.classList.add("exit")
    return new Promise(function(resolve) {
      vnode.dom.addEventListener("animationend", resolve)
    })
  },
  view: function() {
    return m(".fancy", "Hello world")
  }
}

m.mount(document.body, Toggler)

The snippet requires the latest version of Mithril.js framework. It is ideal for beginners showing some basic recipes.

In this example we can see an example of Mithril.js' m.mount API method, besides it core m() hyperscript function. It is also showing the onbeforeremove hook, which is one of several Mithril.js' lifecycle methods. We can also see the usecase of virtual DOM nodes (Vnodes) that is a JavaScript data structure describing a DOM tree.

The code sample was authored by mithril. It was last modified on 19 October 2021. Want to see more examples written by mithril? Then Click here.

Contribute

Do you see some improvements, that could be addressed here? Then let me know by opening an issue. As an alternative, you can fork the repository on GitHub, push your commits and send a pull request. To start your work, click on the edit link below. Thank you for contributing to this repo.

See more code examples  •  Edit this example on GitHub