1

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)");
});
DV82XL
  • 5,350
  • 5
  • 30
  • 59
Dennis Ong
  • 51
  • 5
  • 2
    You are missing either `.` or `#` before your selectors `$("spin")` – Carsten Løvbo Andersen Aug 05 '20 at 18:33
  • 1
    @CarstenLøvboAndersen Thank you for your prompt reply. I fixed the ID. But still no spinning animation. Is my CSS Modified Correct? – Dennis Ong Aug 05 '20 at 18:36
  • 1
    Possible duplicate: https://stackoverflow.com/questions/15191058/css-rotation-cross-browser-with-jquery-animate – Twisty Aug 05 '20 at 18:44
  • 2
    Does this answer your question? [CSS rotation cross browser with jquery.animate()](https://stackoverflow.com/questions/15191058/css-rotation-cross-browser-with-jquery-animate) – Yuri Nudelman Aug 06 '20 at 05:35

2 Answers2

1

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

Twisty
  • 30,304
  • 2
  • 26
  • 45
  • 1
    @DennisOng I am glad it helps. If it has answered your question, I hope that you will mark it as the Answer and Upvote it. – Twisty Aug 06 '20 at 20:07
0

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="" />
MajiD
  • 2,420
  • 1
  • 22
  • 32