CSS animation, click-through switch

I try to make the carriage rotate 180 degrees with a click for my dropdown menu. In the solution I'm trying to implement, it changes the carriage class to switch or click-to-switch. The first time I click on it, it rotates, the second time it immediately returns to its original position and then rotates back. I smell dirty code, the easiest way to add this switch rotation animation. Thanks in advance for any help.
Heres my current css:

.toggle-up { animation-name: toggle-up; animation-delay: 0.25s; animation-duration: 0.75s; animation-fill-mode: forwards; } .toggle-down { animation-name: toggle-down; animation-delay: 0.25s; animation-duration: 0.75s; animation-fill-mode: forwards; } /*animations*/ @keyframes toggle-up { 100% { transform: rotate(180deg); } } @keyframes toggle-down { 100% { transform: rotate(180deg); } } 

enter image description here

+8
javascript html css css-animations
source share
2 answers

You don't need keyframe animations for something so simple. If you simply add a class to your icon when clicked, then delete it, this will apply your rotation. Here is a working plunkr using awesome font and simple rotation . This is a simple example, you want to use provider prefixes and know that css transitions do not work in older browsers.

 <div id="container"> <i id="icon" class="fa fa-arrow-down"></i> </div> .fa-arrow-down{ transform: rotate(0deg); transition: transform 1s linear; } .fa-arrow-down.open{ transform: rotate(180deg); transition: transform 1s linear; } (function(document){ var div = document.getElementById('container'); var icon = document.getElementById('icon'); var open = false; div.addEventListener('click', function(){ if(open){ icon.className = 'fa fa-arrow-down'; } else{ icon.className = 'fa fa-arrow-down open'; } open = !open; }); })(document); 
+12
source share
 .square { width: 100px; height: 100px; background-color: #ff0000; transition: all 0.75s 0.25s; } .toggle-up { transform: rotate(180deg); } .toggle-down { transform: rotate(0); } 

You must have an initial state to complete the animation.

Here is an example: codepen

UPDATE

Here is the version without using javascript: codepen

 <label for="checkbox"> <input type="checkbox" id="checkbox"> <div class="square toggle-down"></div> </label> #checkbox { display: none; } .square { width: 100px; height: 100px; background-color: #ff0000; transition: all 0.75s 0.25s; transform: rotate(0); } #checkbox:checked + .square { transform: rotate(180deg); } 

The general idea is to change the block class using Adjacent selector rollers and the checked .. checkbox . P>

+6
source share

All Articles