How can I get a CSS Animation to play with a JavaScript onClick? I currently have:

.classname {
  -webkit-animation-name: cssAnimation;
  -webkit-animation-duration:3s;
  -webkit-animation-iteration-count: 1;
  -webkit-animation-timing-function: ease;
  -webkit-animation-fill-mode: forwards;
}
@-webkit-keyframes cssAnimation {
  from {
    -webkit-transform: rotate(0deg) scale(1) skew(0deg) translate(100px);
  }
  to {
    -webkit-transform: rotate(0deg) scale(2) skew(0deg) translate(100px);
  }
}

How can I apply an onClick?


Solution 1:

Are you sure you only display your page on webkit? Here is the code, passed on safari. The image (id='img') will rotate after button click.

function ani() {
  document.getElementById('img').className = 'classname';
}
.classname {
  -webkit-animation-name: cssAnimation;
  -webkit-animation-duration: 3s;
  -webkit-animation-iteration-count: 1;
  -webkit-animation-timing-function: ease;
  -webkit-animation-fill-mode: forwards;
}

@-webkit-keyframes cssAnimation {
  from {
    -webkit-transform: rotate(0deg) scale(1) skew(0deg) translate(100px);
  }
  to {
    -webkit-transform: rotate(0deg) scale(2) skew(0deg) translate(100px);
  }
}
<input name="" type="button" onclick="ani()" value="Click">
<img id="img" src="https://i.stack.imgur.com/vghKS.png" width="328" height="328" />

Solution 2:

You just use the :active pseudo-class. This is set when you click on any element.

.classname:active {
    /* animation css */
}

Solution 3:

You can achieve this by binding an onclick listener and then adding the animate class like this:

$('#button').onClick(function(){
    $('#target_element').addClass('animate_class_name');
});