Reputation: 87
I have found a solution that partially fits my needs. When pressing a button I need a div to rotate 90 degrees, on next press 90 degrees more etc. And i need another button which would rotate it in the opposite direction the same way. I found a JavaScript Fiddle and slightly modified it, but the problem is that on the button press the div would revert to its original position before each rotate. So its not possible to rotate it more than 90 degrees. How do I fix this? The second question is why would it rotate only once, if I change broderSpacing from "-90" to "90" (button works only once then nothing happens on click)?
HTML
<div id="foo">Text</div>
<button onclick="rotateFoo()">rotate</button>
CSS
#foo {
width:100px;
height:100px;
position:absolute;
top:100px;
left:100px;
border-spacing: 0;
background-color:red;
}
JS
function rotateFoo(){
$('#foo').animate({borderSpacing: -90}, {
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:'slow'
},'linear')
}
Upvotes: 5
Views: 9364
Reputation: 1
Anton's answer was good a good start, but for anyone looking to rotate in two directions, it needs some work. Here's a demo: https://jsfiddle.net/hyrLcw0f/
function rotateLeft(){
var angle = ($('#foo').data('angle')) || 0;
angle -= 90;
$('#foo').css({'transform': 'rotate(' + angle + 'deg)'});
$('#foo').data('angle', angle);
}
function rotateRight(){
var angle = ($('#foo').data('angle')) || 0;
angle += 90;
$('#foo').css({'transform': 'rotate(' + angle + 'deg)'});
$('#foo').data('angle', angle);
}
Upvotes: 0
Reputation: 1058
I have made a little more straightforward example, please see https://jsfiddle.net/HwTMb/1517/
function rotateFoo(){
var angle = ($('#foo').data('angle') + 90) || 90;
$('#foo').css({'transform': 'rotate(' + angle + 'deg)'});
$('#foo').data('angle', angle);
}
Also, I'm not really sure why do you need border-spacing.
Upvotes: 9
Reputation: 5396
You can change this a little and make it the thing what you want:
var rotate=0;
function rotateFoo(){
$('#foo').animate({borderSpacing: -90}, {
step: function(now,fx)
{
rotate+=2.1;
$(this).css('-webkit-transform','rotate('+rotate+'deg)');
$(this).css('-moz-transform','rotate('+rotate+'deg)');
$(this).css('transform','rotate('+rotate+'deg)');
},
duration:'slow'
},'linear')
}
function rotateFoo2(){
$('#foo').animate({borderSpacing: -90}, {
step: function(now,fx)
{
rotate-=2.1;
$(this).css('-webkit-transform','rotate('+rotate+'deg)');
$(this).css('-moz-transform','rotate('+rotate+'deg)');
$(this).css('transform','rotate('+rotate+'deg)');
},
duration:'slow'
},'linear')
}
and HTML:
<div id="foo">Text</div>
<button onclick="rotateFoo()">rotate</button>
<button onclick="rotateFoo2()">rotate</button>
Please see DEMO JSFIDDLE
You can use this js library too Transit
Upvotes: 0