Dennis Ong
Dennis Ong

Reputation: 51

Button On Click Change Rotation of an Image

I have an image that I want to transform in terms of rotation when click on a button.

How do I achieve this in Jquery?

JS Fiddle Link: http://jsfiddle.net/DJ8p7/

$("spin").click(function(){
  $("myImage").css("transform", "rotate(45deg)");
  $("myImage").css("-webkit-transform", "rotate(45deg)");
  $("myImage").css("-ms-transform", "rotate(45deg)");
});

Upvotes: 1

Views: 175

Answers (2)

MajiD
MajiD

Reputation: 2575

It's better to use css transition and simply toggleClass on button click:

$(".rotate").on("click", function(e) {
  $(".image").toggleClass("rotate");
})
$(".rotateX").on("click", function(e) {
  $(".image").toggleClass("rotateX");
})
img {
  display: block;
  margin: 20px;
  transition: transform 1s ease;
}

img.rotate {
  transform: rotate(45deg);
  -webkit-transform: rotate(45deg);
  -ms-transform: rotate(45deg);
}

img.rotateX {
  transform: rotateX(180deg) scaleX(-1);
  -webkit-transform: rotateX(180deg) scaleX(-1);
  -ms-transform: rotateX(180deg) scaleX(-1);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="rotate">
Rotate
</button>
<button class="rotateX">
RotateX
</button>
<img class="image" src="http://lorempixel.com/400/200/" alt="" />

Upvotes: 0

Twisty
Twisty

Reputation: 30893

Consider the following example: https://jsfiddle.net/Twisty/d43tfp2c/11/

JavaScript

$(function() {
  var cDeg = 0;

  function animateRotate(elem, angle) {
    var $elem = $(elem);
    $elem.animate({
      deg: angle
    }, {
      duration: 2000,
      step: function(now) {
        $elem.css({
          transform: 'rotate(' + now + 'deg)'
        });
      }
    });
  }

  $("img").click(function() {
    cDeg += 45;
    /*
    if (cDeg >= 360) {
      cDeg = 0;
    }
    */
    console.log(cDeg);
    animateRotate(this, cDeg);
  });
});

Found under: CSS rotation cross browser with jquery.animate()

Upvotes: 1

Related Questions