Custom JS transitions

While you should generally use CSS for transitions as much as possible, there are some effects that can’t be achieved without JavaScript, such as a typewriter effect:

  1. function typewriter(node, { speed = 50 }) {
  2. const valid = (
  3. node.childNodes.length === 1 &&
  4. node.childNodes[0].nodeType === 3
  5. );
  6. if (!valid) {
  7. throw new Error(`This transition only works on elements with a single text node child`);
  8. }
  9. const text = node.textContent;
  10. const duration = text.length * speed;
  11. return {
  12. duration,
  13. tick: t => {
  14. const i = ~~(text.length * t);
  15. node.textContent = text.slice(0, i);
  16. }
  17. };
  18. }