Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Controlling CSS animations using JQuery

My animation currently works, when :hover is triggered. I would instead like to initiate the animation on a button click but I don't know how to interact with the CSS from JQuery?

//CSS

.mouth{
  top: 268px;
  left: 273px;
  position: relative;
}

.frame:hover .mouth {
  animation-name: talk;
  animation-duration: 0.75s;
  animation-iteration-count: 5;
}

@keyframes talk {
  0%, 100%{
    top: 268px;
    left: 273px;
  }

  50% {
    top: 308px;
    left: 273px;
  }
}

//JQuery

  $('#getQuote').click(function() {

  });
like image 923
sharkdawg Avatar asked Jan 05 '23 16:01

sharkdawg


2 Answers

Replace the :hover with with another class, and add this class to the clicked item with jQuery.
This way, when clicking, the new class will be added and the condition will be met, which triggers the animation.

like image 112
Antony Avatar answered Jan 08 '23 05:01

Antony


This is pretty straight forward. You'll need to modify your CSS a little, however.

Instead of using the :hover selector, you'd want to make this a new class, let's say .StartAnimation. So your CSS becomes

.StartAnimation .mouth{
    animation-name: talk;
    animation-duration: 0.75s;
    animation-iteration-count: 5;
 }

Then, in your JQuery, we simply add (and/or remove) this class:

$('#getQuote').click(function() {
    $('.frame').addClass('StartAnimation');
    // or toggle it, if a second click should undo the animation
    // $('.frame').toggleClass('StartAnimation');
});

Another way to do this, if you want to keep the hover effect, don't want to change your CSS, but still want to animate on a button click as well (maybe when the user clicks something else), would be to use the .trigger() method in JQuery: http://api.jquery.com/trigger/

$('#getQuote').click(function(){
    $('.frame').trigger('mouseenter');
});
like image 36
Cruiser Avatar answered Jan 08 '23 05:01

Cruiser