# Animations

URL: https://ionicframework.com/docs/utilities/animations

## Overview

Ionic Animations is a tool that enables developers to create complex animations in a platform-agnostic manner, without requiring a specific framework or an Ionic app.

Creating efficient animations can be challenging, as developers are limited by the available libraries and hardware resources of the device. Moreover, many animation libraries use a JavaScript-driven approach, which can reduce the scalability of animations and use up CPU time.

Ionic Animations, on the other hand, uses the [Web Animations API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API), which offloads all the computation and running of animations to the browser. This approach allows the browser to optimize the animations and ensure their smooth execution. In cases where Web Animations are not supported, Ionic Animations will fall back to [CSS Animations](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Animations/Using_CSS_animations), which should have a negligible difference in performance.

## Installation

Developers using Angular should install the latest version of `@ionic/angular`. Animations can be created via the `AnimationController` dependency injection.
```tsx
import { Animation, AnimationController } from '@ionic/angular/lazy';

...

constructor(private animationCtrl: AnimationController) {
  const animation: Animation = this.animationCtrl.create()
    .addElement(myElementRef)
    .duration(1000)
    .fromTo('opacity', '1', '0.5');
}
```

Developers using Angular should install the latest version of `@ionic/angular`. Animations can be created via the `AnimationController` dependency injection.
```tsx
import { Animation, AnimationController } from '@ionic/angular';

...

constructor(private animationCtrl: AnimationController) {
  const animation: Animation = this.animationCtrl.create()
    .addElement(myElementRef)
    .duration(1000)
    .fromTo('opacity', '1', '0.5');
}
```

Developers using Ionic Core and JavaScript should install the latest version of `@ionic/core`.
```javascript
import { createAnimation } from 'https://cdn.jsdelivr.net/npm/@ionic/core@latest/dist/esm/index.mjs';

...

const animation = createAnimation()
  .addElement(myElementRef)
  .duration(1000)
  .fromTo('opacity', '1', '0.5');
}
```

Developers using React should install the latest version of `@ionic/react`. React wrappers are in beta. Please report any issues on GitHub!
```tsx
import { CreateAnimation, Animation } from '@ionic/react';

...

<CreateAnimation
  duration={1000}
  fromTo={{
    property: 'opacity',
    fromValue: '1',
    toValue: '0.5'
  }}
>
...
</CreateAnimation>
```

Developers using Ionic Core and TypeScript should install the latest version of `@ionic/core`.
```tsx
import { createAnimation, Animation } from '@ionic/core';

...

const animation: Animation = createAnimation('')
  .addElement(myElementRef)
  .duration(1000)
  .fromTo('opacity', '1', '0.5');
}
```

Developers using Ionic Vue should install the latest version of `@ionic/vue`.
```javascript
import { createAnimation } from '@ionic/vue';
import { ref } from 'vue';

...

const myElementRef = ref();

...

const animation = createAnimation()
  .addElement(myElementRef.value)
  .duration(1000)
  .fromTo('opacity', '1', '0.5');
}
```

## Basic Animations

In the example below, an animation that changes the opacity on the `ion-card` element and moves it from left to right along the X axis has been created. This animation will run an infinite number of times, and each iteration of the animation will last 1500ms.

By default, all Ionic Animations are paused until the `play` method is called.

**JavaScript**

```html
<ion-card id="card">
  <ion-card-content>Card</ion-card-content>
</ion-card>

<ion-button onclick="animation.play()">Play</ion-button>
<ion-button onclick="animation.pause()">Pause</ion-button>
<ion-button onclick="animation.stop()">Stop</ion-button>

<script>
  var animation = createAnimation()
    .addElement(document.querySelector('#card'))
    .duration(1500)
    .iterations(Infinity)
    .fromTo('transform', 'translateX(0px)', 'translateX(100px)')
    .fromTo('opacity', '1', '0.2');
</script>
```

**Angular**

`src/app/example.component.html`

```html
<ion-card #card>
  <ion-card-content>Card</ion-card-content>
</ion-card>

<ion-button (click)="play()">Play</ion-button>
<ion-button (click)="pause()">Pause</ion-button>
<ion-button (click)="stop()">Stop</ion-button>
```

`src/app/example.component.ts`

```ts
import { Component, ElementRef, ViewChild } from '@angular/core';
import { IonButton, IonCard, IonCardContent } from '@ionic/angular';
import type { Animation } from '@ionic/angular';
import { AnimationController } from '@ionic/angular';

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonButton, IonCard, IonCardContent],
})
export class ExampleComponent {
  @ViewChild(IonCard, { read: ElementRef }) card!: ElementRef<HTMLIonCardElement>;

  private animation!: Animation;

  constructor(private animationCtrl: AnimationController) {}

  ngAfterViewInit() {
    this.animation = this.animationCtrl
      .create()
      .addElement(this.card.nativeElement)
      .duration(1500)
      .iterations(Infinity)
      .fromTo('transform', 'translateX(0px)', 'translateX(100px)')
      .fromTo('opacity', '1', '0.2');
  }

  play() {
    this.animation.play();
  }

  pause() {
    this.animation.pause();
  }

  stop() {
    this.animation.stop();
  }
}
```

**React**

```tsx
import React, { useEffect, useRef } from 'react';
import { IonButton, IonCard, IonCardContent, createAnimation } from '@ionic/react';
import type { Animation } from '@ionic/react';

function Example() {
  const cardEl = useRef<HTMLIonCardElement | null>(null);

  const animation = useRef<Animation | null>(null);

  useEffect(() => {
    if (animation.current === null) {
      animation.current = createAnimation()
        .addElement(cardEl.current!)
        .duration(1500)
        .iterations(Infinity)
        .fromTo('transform', 'translateX(0px)', 'translateX(100px)')
        .fromTo('opacity', '1', '0.2');
    }
  }, [cardEl]);

  const play = () => {
    animation.current?.play();
  };
  const pause = () => {
    animation.current?.pause();
  };
  const stop = () => {
    animation.current?.stop();
  };

  return (
    <>
      <IonCard ref={cardEl}>
        <IonCardContent>Card</IonCardContent>
      </IonCard>

      <IonButton onClick={play}>Play</IonButton>
      <IonButton onClick={pause}>Pause</IonButton>
      <IonButton onClick={stop}>Stop</IonButton>
    </>
  );
}
export default Example;
```

**Vue**

```vue
<template>
  <ion-card ref="cardEl">
    <ion-card-content>Card</ion-card-content>
  </ion-card>

  <ion-button @click="play()">Play</ion-button>
  <ion-button @click="pause()">Pause</ion-button>
  <ion-button @click="stop()">Stop</ion-button>
</template>

<script setup lang="ts">
import { IonButton, IonCard, IonCardContent, createAnimation } from '@ionic/vue';
import type { Animation } from '@ionic/vue';
import { ref, onMounted } from 'vue';

const cardEl = ref(null);

let animation: Animation;

onMounted(() => {
  animation = createAnimation()
    .addElement(cardEl.value.$el)
    .duration(1500)
    .iterations(Infinity)
    .fromTo('transform', 'translateX(0px)', 'translateX(100px)')
    .fromTo('opacity', '1', '0.2');
});

const play = () => animation.play();
const pause = () => animation.pause();
const stop = () => animation.stop();
</script>
```

## Keyframe Animations

Ionic Animations allows you to control the intermediate steps in an animation using keyframes. Any valid CSS property can be used here, and you can even use CSS Variables as values.

Hyphenated CSS properties should be written using camel case when writing keyframes. For example, `border-radius` should be written as `borderRadius`. This also applies to the `fromTo()`, `from(),` and `to()` methods.

**JavaScript**

```html
<ion-card id="card" style="width: 80px; --width: 160px;">
  <ion-card-content>Card</ion-card-content>
</ion-card>
<ion-button onclick="animation.play()">Play</ion-button>
<ion-button onclick="animation.pause()">Pause</ion-button>
<ion-button onclick="animation.stop()">Stop</ion-button>

<script>
  var animation = createAnimation()
    .addElement(document.querySelector('#card'))
    .duration(3000)
    .iterations(Infinity)
    .keyframes([
      { offset: 0, width: '80px' },
      { offset: 0.72, width: 'var(--width)' },
      { offset: 1, width: '240px' },
    ]);
</script>
```

**Angular**

`src/app/example.component.html`

```html
<ion-card #card style="width: 80px; --width: 160px;">
  <ion-card-content>Card</ion-card-content>
</ion-card>
<ion-button (click)="play()">Play</ion-button>
<ion-button (click)="pause()">Pause</ion-button>
<ion-button (click)="stop()">Stop</ion-button>
```

`src/app/example.component.ts`

```ts
import { Component, ElementRef, ViewChild } from '@angular/core';
import { IonButton, IonCard, IonCardContent } from '@ionic/angular';
import type { Animation } from '@ionic/angular';
import { AnimationController } from '@ionic/angular';

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonButton, IonCard, IonCardContent],
})
export class ExampleComponent {
  @ViewChild(IonCard, { read: ElementRef }) card!: ElementRef<HTMLIonCardElement>;

  private animation!: Animation;

  constructor(private animationCtrl: AnimationController) {}

  ngAfterViewInit() {
    this.animation = this.animationCtrl
      .create()
      .addElement(this.card.nativeElement)
      .duration(3000)
      .iterations(Infinity)
      .keyframes([
        { offset: 0, width: '80px' },
        { offset: 0.72, width: 'var(--width)' },
        { offset: 1, width: '240px' },
      ]);
  }

  play() {
    this.animation.play();
  }

  pause() {
    this.animation.pause();
  }

  stop() {
    this.animation.stop();
  }
}
```

**React**

```tsx
import React, { useEffect, useRef } from 'react';
import { IonButton, IonCard, IonCardContent, createAnimation } from '@ionic/react';
import type { Animation } from '@ionic/react';

function Example() {
  const cardEl = useRef<HTMLIonCardElement | null>(null);

  const animation = useRef<Animation | null>(null);

  useEffect(() => {
    if (animation.current === null) {
      animation.current = createAnimation()
        .addElement(cardEl.current!)
        .duration(3000)
        .iterations(Infinity)
        .keyframes([
          { offset: 0, width: '80px' },
          { offset: 0.72, width: 'var(--width)' },
          { offset: 1, width: '240px' },
        ]);
    }
  }, [cardEl]);

  const play = () => {
    animation.current?.play();
  };
  const pause = () => {
    animation.current?.pause();
  };
  const stop = () => {
    animation.current?.stop();
  };

  return (
    <>
      <IonCard ref={cardEl} style={{ width: '80px', '--width': '160px' } as React.CSSProperties}>
        <IonCardContent>Card</IonCardContent>
      </IonCard>
      <IonButton onClick={play}>Play</IonButton>
      <IonButton onClick={pause}>Pause</IonButton>
      <IonButton onClick={stop}>Stop</IonButton>
    </>
  );
}
export default Example;
```

**Vue**

```vue
<template>
  <ion-card ref="cardEl">
    <ion-card-content>Card</ion-card-content>
  </ion-card>
  <ion-button @click="play()">Play</ion-button>
  <ion-button @click="pause()">Pause</ion-button>
  <ion-button @click="stop()">Stop</ion-button>
</template>

<script setup lang="ts">
import { IonButton, IonCard, IonCardContent, createAnimation } from '@ionic/vue';
import type { Animation } from '@ionic/vue';
import { ref, onMounted } from 'vue';

const cardEl = ref(null);

let animation: Animation;

onMounted(() => {
  animation = createAnimation()
    .addElement(cardEl.value.$el)
    .duration(3000)
    .iterations(Infinity)
    .keyframes([
      { offset: 0, width: '80px' },
      { offset: 0.72, width: 'var(--width)' },
      { offset: 1, width: '240px' },
    ]);
});

const play = () => animation.play();
const pause = () => animation.pause();
const stop = () => animation.stop();
</script>

<style>
ion-card {
  width: 80px;
  --width: 160px;
}
</style>
```

In the example above, the card element will transition from its initial width, to a width defined by the `--width` variable, and then transition on to the final width.

Each keyframe object contains an `offset` property. `offset` is a value between 0 and 1 that defines the keyframe step. Offset values must go in ascending order and cannot repeat.

## Grouped Animations

Multiple elements can be animated at the same time and controlled via a single parent animation object. Child animations inherit properties such as duration, easing, and iterations unless otherwise specified. A parent animation's `onFinish` callback will not be called until all child animations have completed.

This example shows 3 child animations controlled by a single parent animation. Animations `cardA` and `cardB` inherit the parent animation's duration of 2000ms, but animation `cardC` has a duration of 5000ms since it was explicitly set.

**JavaScript**

```html
<ion-card id="card-a">
  <ion-card-content>Card 1</ion-card-content>
</ion-card>

<ion-card id="card-b">
  <ion-card-content>Card 2</ion-card-content>
</ion-card>

<ion-card id="card-c">
  <ion-card-content>Card 3</ion-card-content>
</ion-card>

<ion-button onclick="animation.play()">Play</ion-button>
<ion-button onclick="animation.pause()">Pause</ion-button>
<ion-button onclick="animation.stop()">Stop</ion-button>

<script>
  const cardA = createAnimation()
    .addElement(document.querySelector('#card-a'))
    .keyframes([
      { offset: 0, transform: 'scale(1) rotate(0)' },
      { offset: 0.5, transform: 'scale(1.5) rotate(45deg)' },
      { offset: 1, transform: 'scale(1) rotate(0) ' },
    ]);

  const cardB = createAnimation()
    .addElement(document.querySelector('#card-b'))
    .keyframes([
      { offset: 0, transform: 'scale(1)', opacity: '1' },
      { offset: 0.5, transform: 'scale(1.5)', opacity: '0.3' },
      { offset: 1, transform: 'scale(1)', opacity: '1' },
    ]);

  const cardC = createAnimation()
    .addElement(document.querySelector('#card-c'))
    .duration(5000)
    .keyframes([
      { offset: 0, transform: 'scale(1)', opacity: '0.5' },
      { offset: 0.5, transform: 'scale(0.5)', opacity: '1' },
      { offset: 1, transform: 'scale(1)', opacity: '0.5' },
    ]);

  var animation = createAnimation().duration(2000).iterations(Infinity).addAnimation([cardA, cardB, cardC]);
</script>
```

**Angular**

`src/app/example.component.html`

```html
<ion-card>
  <ion-card-content>Card 1</ion-card-content>
</ion-card>

<ion-card>
  <ion-card-content>Card 2</ion-card-content>
</ion-card>

<ion-card>
  <ion-card-content>Card 3</ion-card-content>
</ion-card>

<ion-button (click)="play()">Play</ion-button>
<ion-button (click)="pause()">Pause</ion-button>
<ion-button (click)="stop()">Stop</ion-button>
```

`src/app/example.component.ts`

```ts
import { Component, ElementRef, ViewChildren } from '@angular/core';
import { IonButton, IonCard, IonCardContent } from '@ionic/angular';
import type { QueryList } from '@angular/core';
import type { Animation } from '@ionic/angular';
import { AnimationController } from '@ionic/angular';

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonButton, IonCard, IonCardContent],
})
export class ExampleComponent {
  @ViewChildren(IonCard, { read: ElementRef }) cardElements!: QueryList<ElementRef<HTMLIonCardElement>>;

  private animation!: Animation;

  constructor(private animationCtrl: AnimationController) {}

  ngAfterViewInit() {
    const cardA = this.animationCtrl
      .create()
      .addElement(this.cardElements.get(0)!.nativeElement)
      .keyframes([
        { offset: 0, transform: 'scale(1) rotate(0)' },
        { offset: 0.5, transform: 'scale(1.5) rotate(45deg)' },
        { offset: 1, transform: 'scale(1) rotate(0)' },
      ]);

    const cardB = this.animationCtrl
      .create()
      .addElement(this.cardElements.get(1)!.nativeElement)
      .keyframes([
        { offset: 0, transform: 'scale(1)', opacity: '1' },
        { offset: 0.5, transform: 'scale(1.5)', opacity: '0.3' },
        { offset: 1, transform: 'scale(1)', opacity: '1' },
      ]);

    const cardC = this.animationCtrl
      .create()
      .addElement(this.cardElements.get(2)!.nativeElement)
      .duration(5000)
      .keyframes([
        { offset: 0, transform: 'scale(1)', opacity: '0.5' },
        { offset: 0.5, transform: 'scale(0.5)', opacity: '1' },
        { offset: 1, transform: 'scale(1)', opacity: '0.5' },
      ]);

    this.animation = this.animationCtrl
      .create()
      .duration(2000)
      .iterations(Infinity)
      .addAnimation([cardA, cardB, cardC].filter(Boolean) as Animation[]);
  }

  play() {
    this.animation.play();
  }

  pause() {
    this.animation.pause();
  }

  stop() {
    this.animation.stop();
  }
}
```

**React**

```tsx
import React, { useEffect, useRef } from 'react';
import { IonButton, IonCard, IonCardContent, createAnimation } from '@ionic/react';
import type { Animation } from '@ionic/react';

function Example() {
  const cardAEl = useRef<HTMLIonCardElement | null>(null);
  const cardBEl = useRef<HTMLIonCardElement | null>(null);
  const cardCEl = useRef<HTMLIonCardElement | null>(null);

  const animation = useRef<Animation | null>(null);

  useEffect(() => {
    if (animation.current === null) {
      const cardA = createAnimation()
        .addElement(cardAEl.current!)
        .keyframes([
          { offset: 0, transform: 'scale(1) rotate(0)' },
          { offset: 0.5, transform: 'scale(1.5) rotate(45deg)' },
          { offset: 1, transform: 'scale(1) rotate(0) ' },
        ]);

      const cardB = createAnimation()
        .addElement(cardBEl.current!)
        .keyframes([
          { offset: 0, transform: 'scale(1)', opacity: '1' },
          { offset: 0.5, transform: 'scale(1.5)', opacity: '0.3' },
          { offset: 1, transform: 'scale(1)', opacity: '1' },
        ]);

      const cardC = createAnimation()
        .addElement(cardCEl.current!)
        .duration(5000)
        .keyframes([
          { offset: 0, transform: 'scale(1)', opacity: '0.5' },
          { offset: 0.5, transform: 'scale(0.5)', opacity: '1' },
          { offset: 1, transform: 'scale(1)', opacity: '0.5' },
        ]);

      animation.current = createAnimation().duration(2000).iterations(Infinity).addAnimation([cardA, cardB, cardC]);
    }
  }, [cardAEl, cardBEl, cardCEl]);

  const play = () => {
    animation.current?.play();
  };
  const pause = () => {
    animation.current?.pause();
  };
  const stop = () => {
    animation.current?.stop();
  };

  return (
    <>
      <IonCard ref={cardAEl}>
        <IonCardContent>Card 1</IonCardContent>
      </IonCard>

      <IonCard ref={cardBEl}>
        <IonCardContent>Card 2</IonCardContent>
      </IonCard>

      <IonCard ref={cardCEl}>
        <IonCardContent>Card 3</IonCardContent>
      </IonCard>

      <IonButton onClick={play}>Play</IonButton>
      <IonButton onClick={pause}>Pause</IonButton>
      <IonButton onClick={stop}>Stop</IonButton>
    </>
  );
}
export default Example;
```

**Vue**

```vue
<template>
  <ion-card ref="cardAEl">
    <ion-card-content>Card 1</ion-card-content>
  </ion-card>

  <ion-card ref="cardBEl">
    <ion-card-content>Card 2</ion-card-content>
  </ion-card>

  <ion-card ref="cardCEl">
    <ion-card-content>Card 3</ion-card-content>
  </ion-card>

  <ion-button @click="play()">Play</ion-button>
  <ion-button @click="pause()">Pause</ion-button>
  <ion-button @click="stop()">Stop</ion-button>
</template>

<script setup lang="ts">
import { IonButton, IonCard, IonCardContent, createAnimation } from '@ionic/vue';
import type { Animation } from '@ionic/vue';
import { ref, onMounted } from 'vue';

const cardAEl = ref(null);
const cardBEl = ref(null);
const cardCEl = ref(null);

let animation: Animation;

onMounted(() => {
  const cardA = createAnimation()
    .addElement(cardAEl.value.$el)
    .keyframes([
      { offset: 0, transform: 'scale(1) rotate(0)' },
      { offset: 0.5, transform: 'scale(1.5) rotate(45deg)' },
      { offset: 1, transform: 'scale(1) rotate(0) ' },
    ]);

  const cardB = createAnimation()
    .addElement(cardBEl.value.$el)
    .keyframes([
      { offset: 0, transform: 'scale(1)', opacity: '1' },
      { offset: 0.5, transform: 'scale(1.5)', opacity: '0.3' },
      { offset: 1, transform: 'scale(1)', opacity: '1' },
    ]);

  const cardC = createAnimation()
    .addElement(cardCEl.value.$el)
    .duration(5000)
    .keyframes([
      { offset: 0, transform: 'scale(1)', opacity: '0.5' },
      { offset: 0.5, transform: 'scale(0.5)', opacity: '1' },
      { offset: 1, transform: 'scale(1)', opacity: '0.5' },
    ]);

  animation = createAnimation().duration(2000).iterations(Infinity).addAnimation([cardA, cardB, cardC]);
});

const play = () => animation.play();
const pause = () => animation.pause();
const stop = () => animation.stop();
</script>
```

## Before and After Hooks

Ionic Animations provides hooks that let you alter an element before an animation runs and after an animation completes. These hooks can be used to perform DOM reads and writes as well as add or remove classes and inline styles.

This example sets an inline filter which inverts the background color of the card by `75%` prior to the animation starting. Once the animation finishes, the box shadow on the element is set to `rgba(255, 0, 50, 0.4) 0px 4px 16px 6px`, a red glow, and the inline filter is cleared. The animation must be stopped in order to remove the box shadow and play it with the filter again.

Refer to [Methods](#methods) for a complete list of hooks.

**JavaScript**

```html
<ion-card id="card">
  <ion-card-content>Card</ion-card-content>
</ion-card>

<ion-button onclick="animation.play()">Play</ion-button>
<ion-button onclick="animation.pause()">Pause</ion-button>
<ion-button onclick="animation.stop()">Stop</ion-button>

<script>
  var animation = createAnimation()
    .addElement(document.querySelector('#card'))
    .duration(2000)
    .beforeStyles({
      filter: 'invert(75%)',
    })
    .beforeClearStyles(['box-shadow'])
    .afterStyles({
      'box-shadow': 'rgba(255, 0, 50, 0.4) 0px 4px 16px 6px',
    })
    .afterClearStyles(['filter'])
    .keyframes([
      { offset: 0, transform: 'scale(1)' },
      { offset: 0.5, transform: 'scale(1.5)' },
      { offset: 1, transform: 'scale(1)' },
    ]);
</script>
```

**Angular**

`src/app/example.component.html`

```html
<ion-card>
  <ion-card-content>Card</ion-card-content>
</ion-card>

<ion-button (click)="play()">Play</ion-button>
<ion-button (click)="pause()">Pause</ion-button>
<ion-button (click)="stop()">Stop</ion-button>
```

`src/app/example.component.ts`

```ts
import { Component, ElementRef, ViewChildren } from '@angular/core';
import { IonButton, IonCard, IonCardContent } from '@ionic/angular';
import type { QueryList } from '@angular/core';
import type { Animation } from '@ionic/angular';
import { AnimationController } from '@ionic/angular';

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonButton, IonCard, IonCardContent],
})
export class ExampleComponent {
  @ViewChildren(IonCard, { read: ElementRef }) cardElements!: QueryList<ElementRef<HTMLIonCardElement>>;

  private animation!: Animation;

  constructor(private animationCtrl: AnimationController) {}

  ngAfterViewInit() {
    const cardEl = this.cardElements.get(0);

    const card = cardEl
      ? this.animationCtrl
          .create()
          .addElement(cardEl.nativeElement)
          .duration(2000)
          .beforeStyles({
            filter: 'invert(75%)',
          })
          .beforeClearStyles(['box-shadow'])
          .afterStyles({
            'box-shadow': 'rgba(255, 0, 50, 0.4) 0px 4px 16px 6px',
          })
          .afterClearStyles(['filter'])
          .keyframes([
            { offset: 0, transform: 'scale(1)' },
            { offset: 0.5, transform: 'scale(1.5)' },
            { offset: 1, transform: 'scale(1)' },
          ])
      : null;

    if (card) {
      this.animation = this.animationCtrl.create().duration(2000).addAnimation([card]);
    }
  }

  play() {
    this.animation.play();
  }

  pause() {
    this.animation.pause();
  }

  stop() {
    this.animation.stop();
  }
}
```

**React**

```tsx
import React, { useEffect, useRef } from 'react';
import { IonButton, IonCard, IonCardContent, createAnimation } from '@ionic/react';
import type { Animation } from '@ionic/react';

function Example() {
  const cardEl = useRef<HTMLIonCardElement | null>(null);

  const card = useRef<Animation>();

  useEffect(() => {
    if (!card.current) {
      card.current = createAnimation()
        .addElement(cardEl.current!)
        .duration(2000)
        .beforeStyles({
          filter: 'invert(75%)',
        })
        .beforeClearStyles(['box-shadow'])
        .afterStyles({
          'box-shadow': 'rgba(255, 0, 50, 0.4) 0px 4px 16px 6px',
        })
        .afterClearStyles(['filter'])
        .keyframes([
          { offset: 0, transform: 'scale(1)' },
          { offset: 0.5, transform: 'scale(1.5)' },
          { offset: 1, transform: 'scale(1)' },
        ]);
    }
  }, [cardEl]);

  const play = async () => {
    await card.current?.play();
  };
  const pause = () => {
    card.current?.pause();
  };
  const stop = () => {
    card.current?.stop();
  };

  return (
    <>
      <IonCard ref={cardEl}>
        <IonCardContent>Card</IonCardContent>
      </IonCard>

      <IonButton id="play" onClick={play}>
        Play
      </IonButton>
      <IonButton id="pause" onClick={pause}>
        Pause
      </IonButton>
      <IonButton id="stop" onClick={stop}>
        Stop
      </IonButton>
    </>
  );
}
export default Example;
```

**Vue**

```vue
<template>
  <ion-card ref="cardEl">
    <ion-card-content>Card</ion-card-content>
  </ion-card>

  <ion-button @click="play()">Play</ion-button>
  <ion-button @click="pause()">Pause</ion-button>
  <ion-button @click="stop()">Stop</ion-button>
</template>

<script setup lang="ts">
import { IonButton, IonCard, IonCardContent, createAnimation } from '@ionic/vue';
import type { Animation } from '@ionic/vue';
import { ref, onMounted } from 'vue';

const cardEl = ref(null);

let card: Animation | undefined;

onMounted(() => {
  card = createAnimation()
    .addElement(cardEl.value.$el)
    .duration(2000)
    .beforeStyles({
      filter: 'invert(75%)',
    })
    .beforeClearStyles(['box-shadow'])
    .afterStyles({
      'box-shadow': 'rgba(255, 0, 50, 0.4) 0px 4px 16px 6px',
    })
    .afterClearStyles(['filter'])
    .keyframes([
      { offset: 0, transform: 'scale(1)' },
      { offset: 0.5, transform: 'scale(1.5)' },
      { offset: 1, transform: 'scale(1)' },
    ]);
});

const play = async () => {
  await card.play();
};
const pause = () => {
  card?.pause();
};
const stop = () => {
  card?.stop();
};
</script>
```

## Chained Animations

Animations can be chained to run one after the other. The `play` method returns a Promise that resolves when the animation has completed.

**JavaScript**

```html
<ion-card id="card-a">
  <ion-card-content>Card 1</ion-card-content>
</ion-card>

<ion-card id="card-b">
  <ion-card-content>Card 2</ion-card-content>
</ion-card>

<ion-card id="card-c">
  <ion-card-content>Card 3</ion-card-content>
</ion-card>

<ion-button onclick="play()">Play</ion-button>
<ion-button onclick="pause()">Pause</ion-button>
<ion-button onclick="stop()">Stop</ion-button>

<script>
  const cardA = createAnimation()
    .addElement(document.querySelector('#card-a'))
    .fill('none')
    .duration(1000)
    .keyframes([
      { offset: 0, transform: 'scale(1) rotate(0)' },
      { offset: 0.5, transform: 'scale(1.2) rotate(45deg)' },
      { offset: 1, transform: 'scale(1) rotate(0)' },
    ]);

  const cardB = createAnimation()
    .addElement(document.querySelector('#card-b'))
    .fill('none')
    .duration(1000)
    .keyframes([
      { offset: 0, transform: 'scale(1)', opacity: '1' },
      { offset: 0.5, transform: 'scale(1.2)', opacity: '0.3' },
      { offset: 1, transform: 'scale(1)', opacity: '1' },
    ]);

  const cardC = createAnimation()
    .addElement(document.querySelector('#card-c'))
    .fill('none')
    .duration(1000)
    .keyframes([
      { offset: 0, transform: 'scale(1)', opacity: '0.5' },
      { offset: 0.5, transform: 'scale(0.8)', opacity: '1' },
      { offset: 1, transform: 'scale(1)', opacity: '0.5' },
    ]);

  async function play() {
    await cardA.play();
    await cardB.play();
    await cardC.play();
  }

  function pause() {
    cardA.pause();
    cardB.pause();
    cardC.pause();
  }

  function stop() {
    cardA.stop();
    cardB.stop();
    cardC.stop();
  }
</script>
```

**Angular**

`src/app/example.component.html`

```html
<ion-card>
  <ion-card-content>Card 1</ion-card-content>
</ion-card>

<ion-card>
  <ion-card-content>Card 2</ion-card-content>
</ion-card>

<ion-card>
  <ion-card-content>Card 3</ion-card-content>
</ion-card>

<ion-button (click)="play()">Play</ion-button>
<ion-button (click)="pause()">Pause</ion-button>
<ion-button (click)="stop()">Stop</ion-button>
```

`src/app/example.component.ts`

```ts
import { Component, ElementRef, ViewChildren } from '@angular/core';
import { IonButton, IonCard, IonCardContent } from '@ionic/angular';
import type { QueryList } from '@angular/core';
import type { Animation } from '@ionic/angular';
import { AnimationController } from '@ionic/angular';

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonButton, IonCard, IonCardContent],
})
export class ExampleComponent {
  @ViewChildren(IonCard, { read: ElementRef }) cardElements!: QueryList<ElementRef<HTMLIonCardElement>>;

  private cardA!: Animation | null;
  private cardB!: Animation | null;
  private cardC!: Animation | null;

  constructor(private animationCtrl: AnimationController) {}

  ngAfterViewInit() {
    const cardElA = this.cardElements.get(0);
    const cardElB = this.cardElements.get(1);
    const cardElC = this.cardElements.get(2);

    this.cardA = cardElA
      ? this.animationCtrl
          .create()
          .addElement(cardElA.nativeElement)
          .fill('none')
          .duration(1000)
          .keyframes([
            { offset: 0, transform: 'scale(1) rotate(0)' },
            { offset: 0.5, transform: 'scale(1.2) rotate(45deg)' },
            { offset: 1, transform: 'scale(1) rotate(0)' },
          ])
      : null;

    this.cardB = cardElB
      ? this.animationCtrl
          .create()
          .addElement(cardElB.nativeElement)
          .fill('none')
          .duration(1000)
          .keyframes([
            { offset: 0, transform: 'scale(1)', opacity: '1' },
            { offset: 0.5, transform: 'scale(1.2)', opacity: '0.3' },
            { offset: 1, transform: 'scale(1)', opacity: '1' },
          ])
      : null;

    this.cardC = cardElC
      ? this.animationCtrl
          .create()
          .addElement(cardElC.nativeElement)
          .fill('none')
          .duration(1000)
          .keyframes([
            { offset: 0, transform: 'scale(1)', opacity: '0.5' },
            { offset: 0.5, transform: 'scale(0.8)', opacity: '1' },
            { offset: 1, transform: 'scale(1)', opacity: '0.5' },
          ])
      : null;
  }

  async play() {
    await this.cardA?.play();
    await this.cardB?.play();
    await this.cardC?.play();
  }

  pause() {
    this.cardA?.pause();
    this.cardB?.pause();
    this.cardC?.pause();
  }

  async stop() {
    await this.cardA?.stop();
    await this.cardB?.stop();
    await this.cardC?.stop();
  }
}
```

**React**

```tsx
import React, { useEffect, useRef } from 'react';
import { IonButton, IonCard, IonCardContent, createAnimation } from '@ionic/react';
import type { Animation } from '@ionic/react';

function Example() {
  const cardAEl = useRef<HTMLIonCardElement | null>(null);
  const cardBEl = useRef<HTMLIonCardElement | null>(null);
  const cardCEl = useRef<HTMLIonCardElement | null>(null);

  const cardA = useRef<Animation>();
  const cardB = useRef<Animation>();
  const cardC = useRef<Animation>();

  useEffect(() => {
    if (!cardA.current) {
      cardA.current = createAnimation()
        .addElement(cardAEl.current!)
        .fill('none')
        .duration(1000)
        .keyframes([
          { offset: 0, transform: 'scale(1) rotate(0)' },
          { offset: 0.5, transform: 'scale(1.2) rotate(45deg)' },
          { offset: 1, transform: 'scale(1) rotate(0)' },
        ]);
    }

    if (!cardB.current) {
      cardB.current = createAnimation()
        .addElement(cardBEl.current!)
        .fill('none')
        .duration(1000)
        .keyframes([
          { offset: 0, transform: 'scale(1)', opacity: '1' },
          { offset: 0.5, transform: 'scale(1.2)', opacity: '0.3' },
          { offset: 1, transform: 'scale(1)', opacity: '1' },
        ]);
    }
    if (!cardC.current) {
      cardC.current = createAnimation()
        .addElement(cardCEl.current!)
        .fill('none')
        .duration(1000)
        .keyframes([
          { offset: 0, transform: 'scale(1)', opacity: '0.5' },
          { offset: 0.5, transform: 'scale(0.8)', opacity: '1' },
          { offset: 1, transform: 'scale(1)', opacity: '0.5' },
        ]);
    }
  }, [cardAEl, cardBEl, cardCEl]);

  const play = async () => {
    await cardA.current?.play();
    await cardB.current?.play();
    await cardC.current?.play();
  };
  const pause = () => {
    cardA.current?.pause();
    cardB.current?.pause();
    cardC.current?.pause();
  };
  const stop = () => {
    cardA.current?.stop();
    cardB.current?.stop();
    cardC.current?.stop();
  };

  return (
    <>
      <IonCard ref={cardAEl}>
        <IonCardContent>Card 1</IonCardContent>
      </IonCard>

      <IonCard ref={cardBEl}>
        <IonCardContent>Card 2</IonCardContent>
      </IonCard>

      <IonCard ref={cardCEl}>
        <IonCardContent>Card 3</IonCardContent>
      </IonCard>

      <IonButton onClick={play}>Play</IonButton>
      <IonButton onClick={pause}>Pause</IonButton>
      <IonButton onClick={stop}>Stop</IonButton>
    </>
  );
}
export default Example;
```

**Vue**

```vue
<template>
  <ion-card ref="cardAEl">
    <ion-card-content>Card 1</ion-card-content>
  </ion-card>

  <ion-card ref="cardBEl">
    <ion-card-content>Card 2</ion-card-content>
  </ion-card>

  <ion-card ref="cardCEl">
    <ion-card-content>Card 3</ion-card-content>
  </ion-card>

  <ion-button @click="play()">Play</ion-button>
  <ion-button @click="pause()">Pause</ion-button>
  <ion-button @click="stop()">Stop</ion-button>
</template>

<script setup lang="ts">
import { IonButton, IonCard, IonCardContent, createAnimation } from '@ionic/vue';
import type { Animation } from '@ionic/vue';
import { ref, onMounted } from 'vue';

const cardAEl = ref(null);
const cardBEl = ref(null);
const cardCEl = ref(null);

let cardA: Animation | undefined;
let cardB: Animation | undefined;
let cardC: Animation | undefined;

onMounted(() => {
  cardA = createAnimation()
    .addElement(cardAEl.value.$el)
    .fill('none')
    .duration(1000)
    .keyframes([
      { offset: 0, transform: 'scale(1) rotate(0)' },
      { offset: 0.5, transform: 'scale(1.2) rotate(45deg)' },
      { offset: 1, transform: 'scale(1) rotate(0)' },
    ]);

  cardB = createAnimation()
    .addElement(cardBEl.value.$el)
    .fill('none')
    .duration(1000)
    .keyframes([
      { offset: 0, transform: 'scale(1)', opacity: '1' },
      { offset: 0.5, transform: 'scale(1.2)', opacity: '0.3' },
      { offset: 1, transform: 'scale(1)', opacity: '1' },
    ]);

  cardC = createAnimation()
    .addElement(cardCEl.value.$el)
    .fill('none')
    .duration(1000)
    .keyframes([
      { offset: 0, transform: 'scale(1)', opacity: '0.5' },
      { offset: 0.5, transform: 'scale(0.8)', opacity: '1' },
      { offset: 1, transform: 'scale(1)', opacity: '0.5' },
    ]);
});

const play = async () => {
  await cardA?.play();
  await cardB?.play();
  await cardC?.play();
};
const pause = () => {
  cardA?.pause();
  cardB?.pause();
  cardC?.pause();
};
const stop = () => {
  cardA?.stop();
  cardB?.stop();
  cardC?.stop();
};
</script>
```

## Gesture Animations

Ionic Animations gives developers the ability to create powerful gesture-based animations by integrating seamlessly with [Ionic Gestures](/docs/utilities/gestures.md).

In the following example we are creating a track along which we can drag the card element. Our `animation` object will take care of moving the card element either left or right, and our `gesture` object will instruct the `animation` object which direction to move in.

**JavaScript**

```html
<div class="container">
  <div class="track">
    <ion-card id="card" button="true">
      <ion-card-content>Card</ion-card-content>
    </ion-card>
  </div>
</div>

<p>Drag the square along the track.</p>

<style>
  .container {
    display: flex;
  }

  .track {
    width: 344px;

    background: var(--ion-color-medium);

    padding: 16px;
  }

  ion-card {
    width: 100px;

    box-shadow: none;

    margin: 0px;
  }
</style>

<script>
  let initialStep = 0;
  let started = false;

  const card = document.querySelector('ion-card');

  /**
   * The track is 344px wide.
   * The card is 100px wide.
   * We want 16px of margin on each end of the track.
   */
  const MAX_TRANSLATE = 344 - 100 - 32;

  const animation = createAnimation()
    .addElement(card)
    .duration(1000)
    .fromTo('transform', 'translateX(0)', `translateX(${MAX_TRANSLATE}px)`);

  const gesture = createGesture({
    el: card,
    threshold: 0,
    gestureName: 'card-drag',
    onMove: (event) => onMove(event),
    onEnd: (event) => onEnd(event),
  });

  gesture.enable(true);

  var onMove = (event) => {
    if (!started) {
      animation.progressStart();
      started = true;
    }

    animation.progressStep(getStep(event));
  };

  var onEnd = (event) => {
    if (!started) {
      return;
    }

    gesture.enable(false);

    const step = getStep(event);
    const shouldComplete = step > 0.5;

    animation.progressEnd(shouldComplete ? 1 : 0, step).onFinish(() => {
      gesture.enable(true);
    });

    initialStep = shouldComplete ? MAX_TRANSLATE : 0;
    started = false;
  };

  var clamp = (min, n, max) => {
    return Math.max(min, Math.min(n, max));
  };

  var getStep = (event) => {
    const delta = initialStep + event.deltaX;
    return clamp(0, delta / MAX_TRANSLATE, 1);
  };
</script>
```

**Angular**

`src/app/example.component.html`

```html
<div class="container">
  <div class="track">
    <ion-card id="card" button="true">
      <ion-card-content>Card</ion-card-content>
    </ion-card>
  </div>

  <p>Drag the square along the track.</p>
</div>
```

`src/app/example.component.ts`

```ts
import { Component, ElementRef, ViewChild } from '@angular/core';
import { AnimationController, GestureController, IonCard, IonCardContent } from '@ionic/angular';
import type { Animation, Gesture, GestureDetail } from '@ionic/angular';

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonCard, IonCardContent],
})
export class ExampleComponent {
  @ViewChild(IonCard, { read: ElementRef }) card!: ElementRef<HTMLIonCardElement>;

  private animation!: Animation;
  private gesture!: Gesture;
  private started = false;
  private initialStep = 0;

  /**
   * The track is 344px wide.
   * The card is 100px wide.
   * We want 16px of margin on each end of the track.
   */
  private readonly MAX_TRANSLATE = 344 - 100 - 32;

  constructor(
    private animationCtrl: AnimationController,
    private gestureCtrl: GestureController
  ) {}

  private onMove(event: GestureDetail) {
    if (!this.started) {
      this.animation.progressStart();
      this.started = true;
    }

    this.animation.progressStep(this.getStep(event));
  }

  private onEnd(event: GestureDetail) {
    if (!this.started) {
      return;
    }

    this.gesture.enable(false);

    const step = this.getStep(event);
    const shouldComplete = step > 0.5;

    this.animation.progressEnd(shouldComplete ? 1 : 0, step).onFinish(() => {
      this.gesture.enable(true);
    });

    this.initialStep = shouldComplete ? this.MAX_TRANSLATE : 0;
    this.started = false;
  }

  private clamp(min: number, n: number, max: number) {
    return Math.max(min, Math.min(n, max));
  }

  private getStep(event: GestureDetail) {
    const delta = this.initialStep + event.deltaX;
    return this.clamp(0, delta / this.MAX_TRANSLATE, 1);
  }

  ngAfterViewInit() {
    this.animation = this.animationCtrl
      .create()
      .addElement(this.card.nativeElement)
      .duration(1000)
      .fromTo('transform', 'translateX(0)', `translateX(${this.MAX_TRANSLATE}px)`);

    const gesture = (this.gesture = this.gestureCtrl.create({
      el: this.card.nativeElement,
      threshold: 0,
      gestureName: 'card-drag',
      onMove: (event) => this.onMove(event),
      onEnd: (event) => this.onEnd(event),
    }));

    gesture.enable(true);
  }
}
```

`src/app/example.component.css`

```css
.container {
  flex-direction: column;
}

.track {
  width: 344px;
  background: var(--ion-color-medium);
  padding: 16px;
}

ion-card {
  width: 100px;
  box-shadow: none;
  margin: 0px;
}
```

**React**

`src/main.tsx`

```tsx
import React, { useEffect, useRef } from 'react';
import { IonCard, IonCardContent, createAnimation, createGesture } from '@ionic/react';
import type { Animation, Gesture, GestureDetail } from '@ionic/react';

import './main.css';

function Example() {
  const cardEl = useRef<HTMLIonCardElement | null>(null);
  const animation = useRef<Animation | null>(null);
  const gesture = useRef<Gesture | null>(null);
  const initialStep = useRef<number>(0);
  const started = useRef<boolean>(false);

  useEffect(() => {
    if (animation.current === null) {
      /**
       * The track is 344px wide.
       * The card is 100px wide.
       * We want 16px of margin on each end of the track.
       */
      const MAX_TRANSLATE = 344 - 100 - 32;

      animation.current = createAnimation()
        .addElement(cardEl.current!)
        .duration(1000)
        .fromTo('transform', 'translateX(0)', `translateX(${MAX_TRANSLATE}px)`);

      gesture.current = createGesture({
        el: cardEl.current!,
        threshold: 0,
        gestureName: 'card-drag',
        onMove: (event) => onMove(event),
        onEnd: (event) => onEnd(event),
      });

      gesture.current.enable(true);

      const onMove = (event: GestureDetail) => {
        if (!started.current) {
          animation.current!.progressStart();
          started.current = true;
        }

        animation.current!.progressStep(getStep(event));
      };

      const onEnd = (event: GestureDetail) => {
        if (!started.current) {
          return;
        }

        gesture.current!.enable(false);

        const step = getStep(event);
        const shouldComplete = step > 0.5;

        animation.current!.progressEnd(shouldComplete ? 1 : 0, step).onFinish(() => {
          gesture.current!.enable(true);
        });

        initialStep.current = shouldComplete ? MAX_TRANSLATE : 0;
        started.current = false;
      };

      const clamp = (min: number, n: number, max: number) => {
        return Math.max(min, Math.min(n, max));
      };

      const getStep = (event: GestureDetail) => {
        const delta = initialStep.current + event.deltaX;
        return clamp(0, delta / MAX_TRANSLATE, 1);
      };
    }
  }, [cardEl]);

  return (
    <>
      <div className="container">
        <div className="track">
          <IonCard id="card" button={true} ref={cardEl}>
            <IonCardContent>Card</IonCardContent>
          </IonCard>
        </div>

        <p>Drag the square along the track.</p>
      </div>
    </>
  );
}
export default Example;
```

`src/main.css`

```css
.container {
  flex-direction: column;
}

.track {
  width: 344px;
  background: var(--ion-color-medium);
  padding: 16px;
}

ion-card {
  width: 100px;
  box-shadow: none;
  margin: 0px;
}
```

**Vue**

```vue
<template>
  <div class="container">
    <div class="track">
      <ion-card id="card" button="true" ref="cardEl">
        <ion-card-content>Card</ion-card-content>
      </ion-card>
    </div>

    <p>Drag the square along the track.</p>
  </div>
</template>

<script setup lang="ts">
import { IonCard, IonCardContent, createAnimation, createGesture } from '@ionic/vue';
import type { GestureDetail } from '@ionic/vue';
import { ref, onMounted } from 'vue';

const cardEl = ref(null);

onMounted(() => {
  let initialStep = 0;
  let started = false;

  /**
   * The track is 344px wide.
   * The card is 100px wide.
   * We want 16px of margin on each end of the track.
   */
  const MAX_TRANSLATE = 344 - 100 - 32;

  const animation = createAnimation()
    .addElement(cardEl.value.$el)
    .duration(1000)
    .fromTo('transform', 'translateX(0)', `translateX(${MAX_TRANSLATE}px)`);

  const gesture = createGesture({
    el: cardEl.value.$el,
    threshold: 0,
    gestureName: 'card-drag',
    onMove: (event) => onMove(event),
    onEnd: (event) => onEnd(event),
  });

  gesture.enable(true);

  const onMove = (event: GestureDetail) => {
    if (!started) {
      animation.progressStart();
      started = true;
    }

    animation.progressStep(getStep(event));
  };

  const onEnd = (event: GestureDetail) => {
    if (!started) {
      return;
    }

    gesture.enable(false);

    const step = getStep(event);
    const shouldComplete = step > 0.5;

    animation.progressEnd(shouldComplete ? 1 : 0, step).onFinish(() => {
      gesture.enable(true);
    });

    initialStep = shouldComplete ? MAX_TRANSLATE : 0;
    started = false;
  };

  const clamp = (min: number, n: number, max: number) => {
    return Math.max(min, Math.min(n, max));
  };

  const getStep = (event: GestureDetail) => {
    const delta = initialStep + event.deltaX;
    return clamp(0, delta / MAX_TRANSLATE, 1);
  };
});
</script>

<style scoped>
.container {
  flex-direction: column;
}

.track {
  width: 344px;
  background: var(--ion-color-medium);
  padding: 16px;
}

ion-card {
  width: 100px;
  box-shadow: none;
  margin: 0px;
}
</style>
```

## Preference-Based Animations

Developers can also tailor their animations to user preferences such as `prefers-reduced-motion` and `prefers-color-scheme` using CSS Variables.

This method works in all supported browsers when creating animations for the first time. Most browsers are also capable of dynamically updating keyframe animations as the CSS Variables change.

Safari does not currently support dynamically updating keyframe animations. For developers who need this kind of support in Safari, they can use [MediaQueryList.addListener()](https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryList/addListener).

**JavaScript**

```html
<ion-card id="card">
  <ion-card-content>Card</ion-card-content>
</ion-card>

<ion-button onclick="animation.play()">Play</ion-button>
<ion-button onclick="animation.pause()">Pause</ion-button>
<ion-button onclick="animation.stop()">Stop</ion-button>

<script>
  var animation = createAnimation()
    .addElement(document.querySelector('#card'))
    .duration(1500)
    .iterations(Infinity)
    .direction('alternate')
    .fromTo('background', 'blue', 'var(--background)');
</script>

<style>
  ion-card {
    color: white;
    opacity: 0.5;
    background: blue;
    margin: 10px;

    --background: red;
  }

  @media (prefers-color-scheme: dark) {
    ion-card {
      --background: green;
    }
  }
</style>
```

**Angular**

`src/app/example.component.html`

```html
<ion-card #card>
  <ion-card-content>Card</ion-card-content>
</ion-card>

<ion-button (click)="play()">Play</ion-button>
<ion-button (click)="pause()">Pause</ion-button>
<ion-button (click)="stop()">Stop</ion-button>
```

`src/app/example.component.ts`

```ts
import { Component, ElementRef, ViewChild } from '@angular/core';
import { IonButton, IonCard, IonCardContent } from '@ionic/angular';
import type { Animation } from '@ionic/angular';
import { AnimationController } from '@ionic/angular';

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['./example.component.css'],
  imports: [IonButton, IonCard, IonCardContent],
})
export class ExampleComponent {
  @ViewChild(IonCard, { read: ElementRef }) card!: ElementRef<HTMLIonCardElement>;

  private animation!: Animation;

  constructor(private animationCtrl: AnimationController) {}

  ngAfterViewInit() {
    this.animation = this.animationCtrl
      .create()
      .addElement(this.card.nativeElement)
      .duration(1500)
      .iterations(Infinity)
      .direction('alternate')
      .fromTo('background', 'blue', 'var(--background)');
  }

  play() {
    this.animation.play();
  }

  pause() {
    this.animation.pause();
  }

  stop() {
    this.animation.stop();
  }
}
```

`src/app/example.component.css`

```css
ion-card {
  color: white;
  opacity: 0.5;
  background: blue;
  margin: 10px;

  --background: red;
}

@media (prefers-color-scheme: dark) {
  ion-card {
    --background: green;
  }
}
```

**React**

`src/main.tsx`

```tsx
import React, { useEffect, useRef } from 'react';
import { IonButton, IonCard, IonCardContent, createAnimation } from '@ionic/react';
import type { Animation } from '@ionic/react';

import './main.css';

function Example() {
  const cardEl = useRef<HTMLIonCardElement | null>(null);

  const animation = useRef<Animation | null>(null);

  useEffect(() => {
    if (animation.current === null) {
      animation.current = createAnimation()
        .addElement(cardEl.current!)
        .duration(1500)
        .iterations(Infinity)
        .direction('alternate')
        .fromTo('background', 'blue', 'var(--background)');
    }
  }, [cardEl]);

  const play = () => {
    animation.current?.play();
  };
  const pause = () => {
    animation.current?.pause();
  };
  const stop = () => {
    animation.current?.stop();
  };

  return (
    <>
      <IonCard ref={cardEl}>
        <IonCardContent>Card</IonCardContent>
      </IonCard>

      <IonButton onClick={play}>Play</IonButton>
      <IonButton onClick={pause}>Pause</IonButton>
      <IonButton onClick={stop}>Stop</IonButton>
    </>
  );
}
export default Example;
```

`src/main.css`

```css
ion-card {
  color: white;
  opacity: 0.5;
  background: blue;
  margin: 10px;

  --background: red;
}

@media (prefers-color-scheme: dark) {
  ion-card {
    --background: green;
  }
}
```

**Vue**

```vue
<template>
  <ion-card ref="cardEl">
    <ion-card-content>Card</ion-card-content>
  </ion-card>

  <ion-button @click="play()">Play</ion-button>
  <ion-button @click="pause()">Pause</ion-button>
  <ion-button @click="stop()">Stop</ion-button>
</template>

<script setup lang="ts">
import { IonButton, IonCard, IonCardContent, createAnimation } from '@ionic/vue';
import type { Animation } from '@ionic/vue';
import { ref, onMounted } from 'vue';

const cardEl = ref(null);

let animation: Animation;

onMounted(() => {
  animation = createAnimation()
    .addElement(cardEl.value.$el)
    .duration(1500)
    .iterations(Infinity)
    .direction('alternate')
    .fromTo('background', 'blue', 'var(--background)');
});

const play = () => animation.play();
const pause = () => animation.pause();
const stop = () => animation.stop();
</script>

<style scoped>
ion-card {
  color: white;
  opacity: 0.5;
  background: blue;
  margin: 10px;

  --background: red;
}

@media (prefers-color-scheme: dark) {
  ion-card {
    --background: green;
  }
}
</style>
```

## Overriding Ionic Component Animations

Certain Ionic components allow developers to provide custom animations. All animations are provided as either properties on the component or are set via a global config.

### Modals

**JavaScript**

```html
<ion-header>
  <ion-toolbar>
    <ion-title>Page</ion-title>
  </ion-toolbar>
</ion-header>
<ion-content class="ion-padding">
  <ion-button id="modal-trigger">Present Modal</ion-button>
  <ion-modal trigger="modal-trigger">
    <ion-header>
      <ion-toolbar>
        <ion-title>Modal</ion-title>
        <ion-buttons slot="end">
          <ion-button onclick="closeModal()">Close</ion-button>
        </ion-buttons>
      </ion-toolbar>
    </ion-header>
    <ion-content class="ion-padding"> Modal Content </ion-content>
  </ion-modal>
</ion-content>

<script>
  const modal = document.querySelector('ion-modal');

  var closeModal = () => {
    modal.dismiss();
  };

  const enterAnimation = (baseEl) => {
    const root = baseEl.shadowRoot;

    const backdropAnimation = createAnimation()
      .addElement(root.querySelector('ion-backdrop'))
      .fromTo('opacity', '0.01', 'var(--backdrop-opacity)');

    const wrapperAnimation = createAnimation()
      .addElement(root.querySelector('.modal-wrapper'))
      .keyframes([
        { offset: 0, opacity: '0', transform: 'scale(0)' },
        { offset: 1, opacity: '0.99', transform: 'scale(1)' },
      ]);

    return createAnimation()
      .addElement(baseEl)
      .easing('ease-out')
      .duration(500)
      .addAnimation([backdropAnimation, wrapperAnimation]);
  };

  const leaveAnimation = (baseEl) => {
    return enterAnimation(baseEl).direction('reverse');
  };

  modal.enterAnimation = enterAnimation;
  modal.leaveAnimation = leaveAnimation;
</script>
```

**Angular**

`src/app/example.component.html`

```html
<ion-header>
  <ion-toolbar>
    <ion-title>Page</ion-title>
  </ion-toolbar>
</ion-header>
<ion-content class="ion-padding">
  <ion-button id="modal-trigger">Present Modal</ion-button>
  <ion-modal trigger="modal-trigger" #modal>
    <ng-template>
      <ion-header>
        <ion-toolbar>
          <ion-title>Modal</ion-title>
          <ion-buttons slot="end">
            <ion-button (click)="closeModal()">Close</ion-button>
          </ion-buttons>
        </ion-toolbar>
      </ion-header>
      <ion-content class="ion-padding"> Modal Content </ion-content>
    </ng-template>
  </ion-modal>
</ion-content>
```

`src/app/example.component.ts`

```ts
import { Component, ViewChild } from '@angular/core';
import { IonButton, IonButtons, IonContent, IonHeader, IonModal, IonTitle, IonToolbar } from '@ionic/angular';
import { AnimationController } from '@ionic/angular';

@Component({
  selector: 'app-example',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css'],
  imports: [IonButton, IonButtons, IonContent, IonHeader, IonModal, IonTitle, IonToolbar],
})
export class ExampleComponent {
  @ViewChild('modal', { static: true }) modal!: IonModal;

  constructor(private animationCtrl: AnimationController) {}

  ngOnInit() {
    const enterAnimation = (baseEl: HTMLElement) => {
      const root = baseEl.shadowRoot;

      const backdropElement = root?.querySelector('ion-backdrop');
      const wrapperElement = root?.querySelector('.modal-wrapper');

      const backdropAnimation = this.animationCtrl
        .create()
        .addElement(backdropElement || baseEl)
        .fromTo('opacity', '0.01', 'var(--backdrop-opacity)');

      const wrapperAnimation = this.animationCtrl.create();

      if (wrapperElement) {
        wrapperAnimation.addElement(wrapperElement).keyframes([
          { offset: 0, opacity: '0', transform: 'scale(0)' },
          { offset: 1, opacity: '0.99', transform: 'scale(1)' },
        ]);
      }

      return this.animationCtrl
        .create()
        .addElement(baseEl)
        .easing('ease-out')
        .duration(500)
        .addAnimation([backdropAnimation, wrapperAnimation]);
    };

    const leaveAnimation = (baseEl: HTMLElement) => {
      return enterAnimation(baseEl).direction('reverse');
    };

    this.modal.enterAnimation = enterAnimation;
    this.modal.leaveAnimation = leaveAnimation;
  }

  closeModal() {
    this.modal.dismiss();
  }
}
```

**React**

```tsx
import React, { useRef } from 'react';
import {
  IonButton,
  IonButtons,
  IonContent,
  IonHeader,
  IonModal,
  IonToolbar,
  IonTitle,
  createAnimation,
} from '@ionic/react';

function Example() {
  const modalEl = useRef<HTMLIonModalElement>(null);

  const enterAnimation = (baseEl: HTMLElement) => {
    const root = baseEl.shadowRoot!;

    const backdropAnimation = createAnimation()
      .addElement(root.querySelector('ion-backdrop')!)
      .fromTo('opacity', '0.01', 'var(--backdrop-opacity)');

    const wrapperAnimation = createAnimation()
      .addElement(root.querySelector('.modal-wrapper')!)
      .keyframes([
        { offset: 0, opacity: '0', transform: 'scale(0)' },
        { offset: 1, opacity: '0.99', transform: 'scale(1)' },
      ]);

    return createAnimation()
      .addElement(baseEl)
      .easing('ease-out')
      .duration(500)
      .addAnimation([backdropAnimation, wrapperAnimation]);
  };

  const leaveAnimation = (baseEl: HTMLElement) => {
    return enterAnimation(baseEl).direction('reverse');
  };

  const closeModal = () => {
    modalEl.current?.dismiss();
  };

  return (
    <>
      <IonHeader>
        <IonToolbar>
          <IonTitle>Page</IonTitle>
        </IonToolbar>
      </IonHeader>
      <IonContent className="ion-padding">
        <IonButton id="modal-trigger">Present Modal</IonButton>
        <IonModal trigger="modal-trigger" ref={modalEl} enterAnimation={enterAnimation} leaveAnimation={leaveAnimation}>
          <IonHeader>
            <IonToolbar>
              <IonTitle>Modal</IonTitle>
              <IonButtons slot="end">
                <IonButton onClick={closeModal}>Close</IonButton>
              </IonButtons>
            </IonToolbar>
          </IonHeader>
          <IonContent className="ion-padding">Modal Content</IonContent>
        </IonModal>
      </IonContent>
    </>
  );
}
export default Example;
```

**Vue**

```vue
<template>
  <ion-header>
    <ion-toolbar>
      <ion-title>Page</ion-title>
    </ion-toolbar>
  </ion-header>
  <ion-content class="ion-padding">
    <ion-button id="modal-trigger">Present Modal</ion-button>
    <ion-modal trigger="modal-trigger" ref="modalEl" :enterAnimation="enterAnimation" :leaveAnimation="leaveAnimation">
      <ion-header>
        <ion-toolbar>
          <ion-title>Modal</ion-title>
          <ion-buttons slot="end">
            <ion-button @click="closeModal()">Close</ion-button>
          </ion-buttons>
        </ion-toolbar>
      </ion-header>
      <ion-content class="ion-padding"> Modal Content </ion-content>
    </ion-modal>
  </ion-content>
</template>

<script setup lang="ts">
import {
  IonButton,
  IonButtons,
  IonContent,
  IonHeader,
  IonModal,
  IonToolbar,
  IonTitle,
  createAnimation,
} from '@ionic/vue';
import { ref } from 'vue';

const modalEl = ref(null);

const enterAnimation = (baseEl: HTMLElement) => {
  const root = baseEl.shadowRoot;

  const backdropAnimation = createAnimation()
    .addElement(root!.querySelector('ion-backdrop')!)
    .fromTo('opacity', '0.01', 'var(--backdrop-opacity)');

  const wrapperAnimation = createAnimation()
    .addElement(root!.querySelector('.modal-wrapper')!)
    .keyframes([
      { offset: 0, opacity: '0', transform: 'scale(0)' },
      { offset: 1, opacity: '0.99', transform: 'scale(1)' },
    ]);

  return createAnimation()
    .addElement(baseEl)
    .easing('ease-out')
    .duration(500)
    .addAnimation([backdropAnimation, wrapperAnimation]);
};

const leaveAnimation = (baseEl: HTMLElement) => {
  return enterAnimation(baseEl).direction('reverse');
};

const closeModal = () => {
  modalEl.value?.$el.dismiss();
};
</script>
```

## Performance Considerations

CSS and Web Animations are usually handled on the compositor thread. This is different than the main thread where layout, painting, styling, and your JavaScript is executed. It is recommended that you prefer using properties that can be handled on the compositor thread for optimal animation performance.

Animating properties such as `height` and `width` cause additional layouts and paints which can cause jank and degrade animation performance. On the other hand, animating properties such as `transform` and `opacity` are highly optimizable by the browser and typically do not cause much jank.

For information on which CSS properties cause layouts or paints to occur, refer to [CSS Triggers](https://csstriggers.com/).

## Debugging

For debugging animations in Chrome, there is a great blog post about inspecting animations using the Chrome DevTools: [https://developers.google.com/web/tools/chrome-devtools/inspect-styles/animations](https://developers.google.com/web/tools/chrome-devtools/inspect-styles/animations).

It is also recommended to assign unique identifiers to your animations. These identifiers will show up in the Animations inspector in Chrome and should make it easier to debug:

```javascript
/**
 * The animation for the .square element should
 * show "my-animation-identifier" in Chrome DevTools.
 */
const animation = createAnimation('my-animation-identifier')
  .addElement(document.querySelector('.square'))
  .duration(1000)
  .fromTo('opacity', '1', '0');
```

## API

This section provides a list of all the methods and properties available on the `Animation` class.

### Interfaces

#### AnimationDirection

```tsx
type AnimationDirection = 'normal' | 'reverse' | 'alternate' | 'alternate-reverse';
```

#### AnimationFill

```tsx
type AnimationFill = 'auto' | 'none' | 'forwards' | 'backwards' | 'both';
```

#### AnimationBuilder

```tsx
type AnimationBuilder = (baseEl: any, opts?: any) => Animation;
```

**Note**

`opts` are additional options that are specific to the custom animation. For example, the sheet modal enter animation includes information for the current breakpoint.

#### AnimationCallbackOptions

```tsx
interface AnimationCallbackOptions {
  /**
   * If true, the associated callback will only be fired once.
   */
  oneTimeCallback: boolean;
}
```

#### AnimationPlayOptions

```tsx
interface AnimationPlayOptions {
  /**
   * If true, the animation will play synchronously.
   * This is the equivalent of running the animation
   * with a duration of 0ms.
   */
  sync: boolean;
}
```

### Properties

| Name | Description |
| --- | --- |
| `childAnimations: Animation[]` | All child animations of a given parent animation. |
| `elements: HTMLElement[]` | All elements attached to an animation. |
| `parentAnimation?: Animation` | The parent animation of a given animation object. |

### Methods

| Name | Description |
| --- | --- |
| `addAnimation(animationToAdd: Animation \| Animation[]): Animation` | Group one or more animations together to be controlled by a parent animation. |
| `addElement(el: Element \| Element[] \| Node \| Node[] \| NodeList): Animation` | Add one or more elements to the animation. |
| `afterAddClass(className: string \| string[]): Animation` | Add a class or array of classes to be added to all elements in an animation after the animation ends. |
| `afterAddRead(readFn: (): void): Animation` | Add a function that performs a DOM read to be run after the animation ends. |
| `afterAddWrite(writeFn: (): void): Animation` | Add a function that performs a DOM write to be run after the animation ends. |
| `afterClearStyles(propertyNames: string[]): Animation` | Add an array of property names to be cleared from the inline styles on all elements in an animation after the animation ends. |
| `afterRemoveClass(className: string \| string[]): Animation` | Add a class or an array of classes to be removed from all elements in an animation after the animation ends. |
| `afterStyles(styles: { [property: string]: any }): Animation` | Add an object of styles to be applied to all elements in an animation after the animation ends. |
| `beforeAddClass(className: string \| string[]): Animation` | Add a class or array of classes to be added to all elements in an animation before the animation starts. |
| `beforeAddRead(readFn: (): void): Animation` | Add a function that performs a DOM read to be run before the animation starts. |
| `beforeAddWrite(writeFn: (): void): Animation` | Add a function that performs a DOM write to be run before the animation starts. |
| `beforeClearStyles(propertyNames: string[]): Animation` | Add an array of property names to be cleared from the inline styles on all elements in an animation before the animation starts. |
| `beforeRemoveClass(className: string \| string[]): Animation` | Add a class or an array of classes to be removed from all elements in an animation before the animation starts. |
| `beforeStyles(styles: { [property: string]: any }): Animation` | Add an object of styles to be applied to all elements in an animation before the animation starts. |
| `direction(direction?: AnimationDirection): Animation` | Set the direction the animation should play in. |
| `delay(delay?: number): Animation` | Set the delay for the start of the animation in milliseconds. |
| `destroy(clearStyleSheets?: boolean): Animation` | Destroy the animation and clear all elements, child animations, and keyframes. |
| `duration(duration?: number): Animation` | Set the duration of the animation in milliseconds. |
| `easing(easing?: string): Animation` | Set the easing of the animation in milliseconds. Refer to [Easing Effects](https://developer.mozilla.org/en-US/docs/Web/API/EffectTiming/easing#Value) for a list of accepted easing values. |
| `from(property: string, value: any): Animation` | Set the start styles of the animation. |
| `fromTo(property: string, fromValue: any, toValue: any): Animation` | Set the start and end styles of the animation. |
| `fill(fill?: AnimationFill): Animation` | Set how the animation applies styles to its elements before and after the animation's execution. |
| `iterations(iterations: number): Animation` | Set the number of times the animation cycle should be played before stopping. |
| `keyframes(keyframes: any[]): Animation` | Set the keyframes for an animation. |
| `onFinish(callback: (didComplete: boolean, animation: Animation): void, opts?: AnimationCallbackOptions): Animation` | Add a callback to be run upon the animation ending. |
| `pause(): Animation` | Pause the animation. |
| `play(opts?: AnimationPlayOptions): Promise<void>` | Play the animation. |
| `progressEnd(playTo?: 0 \| 1, step: number, dur?: number): Animation` | Stop seeking through an animation. |
| `progressStart(forceLinearEasing?: boolean, step?: number): Animation` | Begin seeking through an animation. |
| `progressStep(step: number): Animation` | Seek through an animation. |
| `stop(): Animation` | Stop the animation and reset all elements to their initial state. |
| `to(property: string, value: any): Animation` | Set the end styles of the animation. |
