Ricardo Roa
Ricardo Roa

Reputation: 173

How to trigger animation with jQuery?

I have CSS code that animates an image, but I want to have a button that triggers the animation using jQuery.

This is my css and html code, but it doesn't work:

jQuery.noConflict();
$(document).ready(function() {
  $(".animar").click(function() {
    $('#img4').addClass('uno');
  });
});
#img4:hover {
  animation-name: uno;
  animation-duration: 7s;
}

@keyframes uno {
  20% {
    left: 80px;
  }
  50% {
    left: 190px;
  }
  70% {
    left: 220px
  }
  100% {
    left: 350px;
  }
}
<div id="movimiento">
  <img src="imagenes/kangura.png" class="img-responsive" id="img4">

  <img src="imagenes/corazon.png" class="img-responsive" id="img5">
  <button class="animar">Entregar Corazón</button>
</div>

What changes do I need to make so it will work?

Upvotes: 0

Views: 125

Answers (1)

Jon Uleis
Jon Uleis

Reputation: 18649

You're adding the class uno in jQuery, but you don't have a corresponding CSS rule for .uno.

I've added one and the bare minimum styles to show this working:

$(document).ready(function() {
  $(".animar").click(function() {
    $('#img4').addClass('uno');
  });
});
#img4 {
  position: absolute;
  top: 30px;
}

.uno {
  animation-name: uno;
  animation-duration: 7s;
}

@keyframes uno {
  20% {
    left: 80px;
  }
  50% {
    left: 190px;
  }
  70% {
    left: 220px
  }
  100% {
    left: 350px;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="movimiento">
  <img src="http://placehold.it/200x200" class="img-responsive" id="img4">

  <button class="animar">Entregar Corazón</button>
</div>

Upvotes: 2

Related Questions