Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotate an image 180 degrees on click with jquery with animation

I'm making a drop down navigation and I would like to use an arrow that rotates to toggle it.

I have this https://jsfiddle.net/jaUJm/39/

$(document).ready(function() {
$( ".toggle" ).click( function() {
    $("#image").css({'transform': 'rotate(-180deg)'});
});
});

I'm just not sure how to make it reset, as in, complete the rotation so it's pointing down again when it's clicked the second and subsequent times.

Maybe a .flip class with

.flip { transform: rotate(-180deg);}

and use an if() and addClass()/removeCLass()?

Thank you!

like image 387
Tyler Cardenas Avatar asked Jan 01 '17 01:01

Tyler Cardenas


1 Answers

You can use toggleClass

$(document).ready(function() {
    $( ".toggle" ).click( function() {
        $("#image").toggleClass('flip');
    });
});
#image {
  -moz-transition: transform 1s;
  -webkit-transition: transform 1s;
  transition: transform 1s;
}

.flip {
  transform: rotate(-180deg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<img class="toggle" id="image" src="https://i.imgur.com/uLlPUfM.png"/>
like image 111
Musa Avatar answered Oct 18 '22 17:10

Musa