Art Planteur Art Planteur - 1 year ago 152
jQuery Question

Rotate image with onclick

I try to make a toggle button where my image (an arrow) will be rotated by 180 degrees each click:

<a href='#' onclick='$(\"#divToggle\").slideToggle(\"slow\");'>
<img src='blue_down_arrow.png' onclick='$(this).rotate(180);' /></a>

<div id='divToggle' style='display:none;'>...CONTENT...</div>";

This code toggle my div but the image rotates only for the first click and then stays "up". I am using this :

Answer Source

This is because the value for rotate angle is absolute, not based on the last rotate.

Working code:


var rotate_factor = 0;

function rotateMe(e) {
    rotate_factor += 1;
    var rotate_angle = (180 * rotate_factor) % 360;


<img src='blue_down_arrow.png' onclick='rotateMe(this);' /></a>

Update: Shorter code

var rotate_angle = 0;

<img src='blue_down_arrow.png' onclick='rotate_angle = (rotate_angle + 180) % 360; $(this).rotate(rotate_angle);' /></a>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download