How to make, that when clicking on the block animation was executed in one direction, and when you click on a paragraph - in the other direction (in reverse order, like a transition)?

$(document).ready(function() { $('div').click(function() { $('div').toggleClass('a1').removeClass('a2'); }); $('p').click(function() { $('div').toggleClass('a2').removeClass('a1'); }); }); 
 div { width: 200px; height: 200px; background: black; position: relative; } .a1 { animation: vras 3s forwards; } .a2 { animation: vras 3s alternate-reverse forwards; } @keyframes vras { from { left: 0; } 33% { left: 85%; } 66% { left: 0; } to { left: 500px; } } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div></div> <p>123</p> 

  • When clicking on p , should the black block move smoothly in the opposite direction? - Yuri
  • @Yuri Yes, I’m working on it. - PeGaS
  • What kind of transitions? - Yuri
  • @Yuri without transitions in the sense of without the use of transition - PeGaS
  • PeGaS, I will try to find the answer to this secret :) - Yuri

1 answer 1

Add a second animation with reverse motion. I don’t know exactly why, but you cannot apply one animation back and forth to one element.

 $(document).ready(function(){ $('div').click(function(){ if($(this).hasClass('a1')){ $(this).addClass('a2').removeClass('a1'); }else{ $(this).addClass('a1').removeClass('a2'); }; }); }); 
 div { width: 200px; height: 200px; background: black; position: relative; } .a1 { animation: vras1 3s forwards; } .a2 { animation: vras2 3s forwards; } @keyframes vras1 { from { left: 0; } 33% { left: 85%; } 66% { left: 0; } to { left: 500px; } } @keyframes vras2 { from { left: 500px; } 33% { left: 0; } 66% { left: 85%; } to{ left: 0; } } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div></div> 

  • It is clear thanks - PeGaS
  • So I came to the same conclusion . Unless another replacement of toggleClass with addClass , in my opinion, is good for the code as a whole, but this already toggleClass on what the author needs. - Regent
  • @Regent You are right, so more correctly. In general, ideally, if the class were replaced by a1 and a2 when you click only on the block. I unknowingly put the addition of class a2 on the paragraph. - PeGaS
  • @PeGaS, I can change the answer and show how to do it only on the block - Yuri
  • @Yuri Yeah, good - PeGaS