Search code examples
javascriptcsswebkitcss-animations

Change paused animation's play state to running on click of a link


Using CSS and Javascript (preferably not jQuery as I don't understand as well) how do I set a CSS animation to go from a pause state to a play state triggered when the user clicks a text link (href) as opposed to a button?


Solution

  • It is very simple. Just set the animation-play-state to paused initially and then add a class which sets the animation-play-state to running when the anchor link is clicked.

    Add a return false to the event handler to prevent the default action of the anchor from happening.

    window.onload = function() {
      var els = document.getElementsByClassName("play-link");
      for (var i = 0; i < els.length; i++) {
        els[i].addEventListener('click', function(e) {
          e.target.previousElementSibling.classList.add('play');
          return false;
        });
      }
    }
    div {
      animation: shake 1s infinite;
      animation-play-state: paused;
      border: 1px solid;
      width: 200px;
      height: 100px;
    }
    @keyframes shake {
      from {
        transform: translateX(0px);
      }
      to {
        transform: translateX(200px);
      }
    }
    div.play {
      animation-play-state: running;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>
    <div class='animate'>Some text</div>
    <a href='#' class='play-link'>Play</a>
    <div class='animate'>Some text</div>
    <a href='#' class='play-link'>Play</a>


    You can even toggle between paused and running states by toggling the play class on and off.

    window.onload = function() {
      var els = document.getElementsByClassName("play-link");
      for (var i = 0; i < els.length; i++) {
        els[i].addEventListener('click', function(e) {
          e.target.previousElementSibling.classList.toggle('play');
          return false;
        });
      }
    }
    div {
      animation: shake 4s infinite;
      animation-play-state: paused;
      border: 1px solid;
      width: 200px;
      height: 100px;
    }
    @keyframes shake {
      0% {
        transform: translateX(0px);
      }
      50% {
        transform: translateX(400px);
      }
      100% {
        transform: translateX(0px);
      }  
    }
    div.play {
      animation-play-state: running;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>
    <div class='animate'>Some text</div>
    <a href='#' class='play-link'>Toggle Play State</a>
    <div class='animate'>Some text</div>
    <a href='#' class='play-link'>Toggle Play State</a>