Manage CSS animations using jQuery

My animation works when it works :hover. Instead, I would like to initiate the animation with a click of a button, but I don’t know how to interact with CSSfrom 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() {

  });
+4
source share
6 answers

Add a class to trigger the animation, but listen to the event animationendto remove the added class so that the animation can be started again.

$('#getQuote').click(function() {
  $('.mouth').addClass('animate');
});
$('.mouth').one('animationend', function(ev) {
  $('.mouth').removeClass('animate');
});
.mouth{
  top: 268px;
  left: 273px;
  position: relative;
  
  width: 100px;
  height: 100px;
  background-color: red;
}

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

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

  50% {
    top: 308px;
    left: 273px;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mouth"></div>
<button id="getQuote">Get Quote</button>
Run codeHide result
+1
source

:hover jQuery.
, , .

+4

. CSS.

: hover , ,.StartAnimation. , CSS

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

JQuery (/ ) :

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

, , CSS, (, - ), .trigger() JQuery: http://api.jquery.com/trigger/

$('#getQuote').click(function(){
    $('.frame').trigger('mouseenter');
});
+2

:

$('.mouth').css({
 '<css property>':'<value>',
 '<css property>':'<value>',
 '<css property>':'<value>'...
});
+1

CSS :

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

JS:

$( "#getQuote" ).click(function() {
    $(this).prop('disabled', true); // disabling so animation can't be restarted until done
    $(".mouth").addClass("animated");
    setTimeout(function(){
        $( "#getQuote" ).prop('disabled', false);
        $(".mouth").removeClass("animated");
    }, 750*5)
});
+1

- :

//css
.animation{
   ......
}

//jquery
var animTimeout;
$('#getQuote').click(function() {
    clearTimeout(animTimeout);
    $('.mouth').addClass('animation');
    animTimeout = setTimeout(function(){
        $('.mouth').removeClass('animation');
    }, 'animation duration in ms')
});
0

Source: https://habr.com/ru/post/1667775/


All Articles