javascriptweb-animationsweb-animations-api

How to use WAAPI Document.getAnimations() function to get only WAAPI animation objects


According to the Mozilla Web Animations API docs, "The getAnimations() method of the Document interface returns an array of all Animation objects currently in effect whose target elements are descendants of the document. This array includes CSS Animations, CSS Transitions, and Web Animations."

Is there any way to use this to only add the Web animation objects to the array, excluding the CSS Animations and CSS transitions?

The following code returns all the animations on the document:

        var allAnimations;
        if (typeof document.getAnimations === 'function') {
            allAnimations = document.getAnimations();
        } else {
            allAnimations = document.timeline.getAnimations();
        }

allAnimations array result is this:

Array(72) [ CSSTransition, CSSTransition, CSSTransition, CSSTransition, CSSTransition, CSSTransition, Animation, Animation, Animation, Animation, … ]

I would like it to only consist of the web animations, so like this:

Array(66) [ Animation, Animation, Animation, Animation, Animation, Animation, Animation, Animation, Animation, Animation, … ]

Solution

  • You can check the type of animation you're looking at using instanceof, and use that to filter the list:

    const animations = [
      ...document.getAnimations(),
      new Animation(),
    ];
    
    const isCSSAnimation = x => x instanceof CSSAnimation;
    
    const onlyAnimations = animations.filter(x => x.constructor.name === 'Animation');
    
    console.dir(animations);
    
    console.dir(onlyAnimations);
    .animated {
      -webkit-animation-duration: .5s;
      animation-duration: .5s;
      -webkit-animation-fill-mode: both;
      animation-fill-mode: both;
      -webkit-animation-timing-function: linear;
      animation-timing-function: linear;
      animation-iteration-count: infinite;
      -webkit-animation-iteration-count: infinite;
    }
    @-webkit-keyframes bounce {
      0%, 100% {
        -webkit-transform: translateY(0);
      }
      50% {
        -webkit-transform: translateY(-5px);
      }
    }
    @keyframes bounce {
      0%, 100% {
        transform: translateY(0);
      }
      50% {
        transform: translateY(-5px);
      }
    }
    .bounce {
      -webkit-animation-name: bounce;
      animation-name: bounce;
    }
    #animated-example {
      width: 20px;
      height: 20px;
      background-color: red;
      position: relative;
      top: 100px;
      left: 100px;
      border-radius: 50%;
    }
    hr {
      position: relative;
      top: 92px;
      left: -300px;
      width: 200px;
    }
    <div id="animated-example" class="animated bounce"></div>