2

I want to rotate an image every time I click on it.. I've created a function to do this but the image only rotate the first time I click on it... Moreover, once the image rotate it change automatically the width and height.. How can I keep the same width and height every time??

This is the function:

$(document).ready(function () {
    $("img").click(function () {
      $(this).rotate(45)       
    })
})
AlexGH
  • 2,735
  • 5
  • 43
  • 76

6 Answers6

2

This can easily be done by using just javascript, working example would be like this

<div id="imgWrapper">
    <img src="Desert.jpg" id="image" onclick="rotateBy10Deg(this)">  
</div>

<script>
    var delta =0;
    function rotateBy10Deg(ele){
        ele.style.webkitTransform="rotate("+delta+"deg)";
        delta+=10;
    }
</script>
viveksinghggits
  • 661
  • 14
  • 35
1

The plugin converts the img into a canvas, that's the reason the click not working for second time. Change your jQuery or refer this demo

$(document).ready(function() {
  $("img").click(function() {
    $(this).rotate(45);
  });
  $('body').on('click', 'canvas', function() {
    $(this).rotate(45);
  });
});
Pugazh
  • 9,453
  • 5
  • 33
  • 54
1

I suggest setting max-height and max-width in your CSS file. This will ensure the image doesn't exceed a certain size.

Oliver Kucharzewski
  • 2,523
  • 4
  • 27
  • 51
1

This link might help you out:

Rotate image with onclick

Taken straight from that link in case you don't want to click:

Javascipt

var rotate_factor = 0;

function rotateMe(e) {
    rotate_factor += 1;
    var rotate_angle = (180 * rotate_factor) % 360;
    $(e).rotate({angle:rotate_angle});
}

HTML

<img src='blue_down_arrow.png' onclick='rotateMe(this);' /></a>
Community
  • 1
  • 1
Alex Mac
  • 63
  • 8
1

I think the angle (45 degree) is calculated in reference to its initial angle that is 0. Once the image is in 45 degree it will only have to rotate if the angle changes (eg 90). So the below code may work

$(document).ready(function () {
 var angle = 0;
$("img").click(function () {
      angle = angle+45;
  $(this).rotate(angle); 
})
})
Nabil
  • 355
  • 1
  • 4
  • 11
0

I did it as you suggested, I used css in JQuery:

css:

.rotate:active {
transform: rotate(180deg)
}

JQuery:

 $(document).ready(function () {
        $("img").click(function () {
//forcing img to rotate every time on click()
            if ($(this).css("transform")=='none') {
                $(this).css("transform", "rotate(180deg)");
            }
            else {
                $(this).css("transform","")
            }
        })
    })
AlexGH
  • 2,735
  • 5
  • 43
  • 76
  • I changed the degrees to 180 instead of 45 because I realized it's better for what I want to do... – AlexGH Apr 29 '16 at 04:36