0

I would like to rotate an object exactly as the fiddle: http://jsfiddle.net/nqC6T/ however, I do not have the JQuery library available in my project.

 var angle = 0;
    $(document).ready(function () {
        $('#rotate').click(function () {
            angle += 90;
            $('#div1').animate({ rotate: angle }, {
                step: function (now, fx) {
                    $(this).css('-webkit-transform', 'rotate(' + now + 'deg)');
                    $(this).css('-moz-transform', 'rotate(' + now + 'deg)');
                    $(this).css('transform', 'rotate(' + now + 'deg)');
                },
                duration: 3000
            }, 'linear');
        });
    });

Would this be possible in plain JavaScript?

Thanks!

2
  • 1
    Yes it's possible. Commented Jan 2, 2018 at 12:56
  • You can do it with CSS3 Animations. Commented Jan 2, 2018 at 12:57

2 Answers 2

3

A plain Javascript based solution is as follows:

var obj = document.getElementById("div1");
var total = 100;
var current = 0;

setInterval(function(){ 

 if (current < total) {
      current += 1;
        obj.style.transform = 'rotate('+current+'deg)';
 }
}, 1);

This is just an example. You can definitely improve this code further. As mentioned by Mohammad, you can also use CSS3 based animations.

Sign up to request clarification or add additional context in comments.

Comments

0

You could add a 'rate of speed' and 'initial rotate position' to the element you wish to rotate, by simply using a closure to automatically return a given rotational increase/decrease rate:

var division=document.getElementById("rotdiv");

function rotElem(startpos,rate){
  return function(mult){ 
  return division.style="transform:rotate("+ startpos+ mult*rate++ +"deg)";};
}
var rotelem = rotElem(0,1);
var atspeedof = setInterval(rotelem.bind(null),1000,10);

rotElem(0,1) You define optional start position '0' of the element before starting rotate and the self-increasing 'unit' of change return by the closure.

setInterval(rotelem.bind(null),1000,10) You call setInterval to run the closure at each second AND passing the value '10' as the multiplier for the rate speed. Changing the rightmost argument after the setInterval time, increases or decreases rotation.

var division = document.getElementById("rotdiv");

function rotElem(startpos, rate) {
  return function(mult) {
    return division.style = "transform:rotate(" + startpos + mult * rate++ + "deg)";
  };

}
var rotelem = rotElem(0, 1);
var atspeedof = setInterval(rotelem.bind(null), 500, 10);
#rotdiv {
  position: relative;
  margin: auto;
  top: 50px;
  width: 80px;
  height: 80px;
  background-color: gray;
}
<div id='rotdiv'>
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.