is there a way to specify the angle when using
$(this).animate({'left': '+=30px'}, 1000);
I would like
$(this).animate({'48': '+=30px'}, 1000);
the 48 would be the angle
is there a way to specify the angle when using
$(this).animate({'left': '+=30px'}, 1000);
I would like
$(this).animate({'48': '+=30px'}, 1000);
the 48 would be the angle
Share Improve this question asked Jan 16, 2012 at 20:55 thelostthelost 7053 gold badges12 silver badges30 bronze badges2 Answers
Reset to default 11You can specify both left
and top
property:
$(this).animate({left: '+=30px', top: '+=30px'}, 1000);
In this case, the angle would be 45°.
To specify a different angle, first calculate cos(α) and sin(α). The cosinus specifies how far you have to go right, and the sinus how far to go up, to make a distance of 1 pixel in the specified angle. If you want to cover 30 pixels distance instead, multiply the sinus and cosinus results by 30.
I just wanted to correct a mistake in 32bitkid's otherwise excellent example from the best answer by Yogu.
If Math.PI is divded by -180 (instead of 180) it will result in the correct position for the div. 90 degree angle was moving div down instead of up.
$(function() {
var dist = 30;
var angle = 90;
var x = Math.cos(angle*Math.PI/-180) * dist;
var y = Math.sin(angle*Math.PI/-180) * dist;
$("div").animate({'left': '+='+x+'px', 'top': '+='+y+'px'}, 1000);
})
Here's the updated fiddle: http://jsfiddle/9yL8hxnz/