AlexGH
AlexGH

Reputation: 2817

Rotate image every time on click JQuery

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)       
    })
})

Upvotes: 2

Views: 13951

Answers (6)

viveksinghggits
viveksinghggits

Reputation: 680

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>

Upvotes: 2

Nabil
Nabil

Reputation: 353

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); 
})
})

Upvotes: 1

Alex Mac
Alex Mac

Reputation: 63

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>

Upvotes: 1

Oliver Kucharzewski
Oliver Kucharzewski

Reputation: 2665

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

Upvotes: 1

AlexGH
AlexGH

Reputation: 2817

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","")
            }
        })
    })

Upvotes: 0

Pugazh
Pugazh

Reputation: 9561

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);
  });
});

Upvotes: 1

Related Questions