Rotating an image with jQuery with 2 buttons - javascript

I have been trying to rotate an image by 90 degrees when clicked on the right button and rotate it by -90 when click on the left button. My code is here.
I'm trying to create some sort of a loop with a counter set at 0 and looping through the if and else statements. but I didn't get it to work:
HTML:
<button id="left" class="button">left</button>
<img src="images/cartoon.jpg" alt="Cartoon" style="width:304px;height:228px;" id="rotate">
<button id="right" class="button">right</button>
CSS:
#draaien {
}
jQuery:
$(document).ready(function(){
var counter = 0;
$("#left").click(function(){
if (counter == 0){
$("#rotate").css({
"-webkit-transform": "rotate(-90deg)",
"-moz-transform": "rotate(-90deg)",
"transform": "rotate(-90deg)"
teller +=1;
});
counter=0;
$("#rotate").css({
}
}else if($("#right").click()){
$("#rotate").css({
"-webkit-transform": "rotate(90deg)",
"-moz-transform": "rotate(90deg)",
"transform": "rotate(90deg)"
}
});
});
});
Basically I was trying to create some kind of counter that upon clicking "left", it increments by 1 and adds the various CSS elements so it can rotate to the left, and decrementing by -1 so it can rotate to the right (+90), it doesnt seem to have any effect. Thanks!

If I understand, you want to set a variable to track the degree turn and add 90 if right, and subtract 90 if left.
$(document).ready(function() {
var deg = 0;
$(".button").on("click", function() {
if ($(this).is("#left")) {
deg = deg - 90;
} else {
deg = deg + 90;
}
$("#rotate").css({
"-webkit-transform": "rotate(" + deg + "deg)",
"-moz-transform": "rotate(" + deg + "deg)",
transform: "rotate(" + deg + "deg)"
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="left" class="button">left</button>
<img src="https://futurism.com/wp-content/uploads/2015/11/neildegrassetyson.jpg" alt="Cartoon" style="width:304px;height:228px;" id="rotate">
<button id="right" class="button">right</button>

Try this, the point is its a 360 degree rotation, so you need to know how much is currently rotated and how far it should go,
$(document).ready(function(){
$("#left").click(function(){
rotate("#rotate",-90)
});
$("#right").click(function(){
rotate("#rotate",90);
});
});
function rotate(whom,angle)
{
var rv=$(whom).prop("data-rot")?$(whom).prop("data-rot"):0;
rv=rv+1;
n=rv*angle;
if(Math.abs(n)>=360){n=0;rv=0;}
$(whom).css({
"-webkit-transform": "rotate(" + n + "deg)",
"-moz-transform": "rotate(" + n + "deg)",
"transform": "rotate(" + n + "deg)"
});
$(whom).prop("data-rot",rv);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="left" class="button">left</button>
<img src="https://cdn.livechatinc.com/s3/default/eyeCatchers/049.png" alt="Cartoon" style="width:304px;height:228px;" id="rotate">
<button id="right" class="button">right</button>

Your thought was right, setting a counter decrease when rotate left and vice versa, but there is some syntax error in the example given by you.
$("#rotate").css({
"-webkit-transform": "rotate(-90deg)",
"-moz-transform": "rotate(-90deg)",
"transform": "rotate(-90deg)"
teller +=1;
});
taller += 1; was an statement, it should't appear inside of a object. Objects are key,value pairs, seperated by colon, and conjoin by comma.
}else if($("#right").click()){
$("#right").click() is a method accepted a event handler function parameter to bind click event handlers on the element, it returns the jQuery Object.
$("#rotate").css({
}
and this wouldn't clear css on the element.
I wrote a simple example here: https://jsfiddle.net/yzjk4v37/
there is 2 buttons controls the block make rotate left or right

Related

How can I rotate an element to 180deg the back to 0deg using the same button in javascript

the code runs all the way over and over. I need the button to rotate to 180 then back again to 0deg then again to 180 incrementing and decrementing by 45deg
<!DOCTYPE html>
<html>
<head>
<title>ttt</title>
</head>
<body>
<div id="memo" style="position: fixed;margin: 140px;">
_____________
</div>
<button onclick="myfun()">Rotate</button>
<script>
function myfun() {
var i = 0
i += 45;
document.getElementById("memo").style.transform += "rotate(" + i + "deg)";
}
</script>
</body>
</html>
Rotating something by 180 degrees and than back to 0 is the same as rotating it towards 360 right?
Why would you need to rotate it back to 0 if you can just keep increasing by 180?
This should do it.
We start out with direction +
Whenever rotation reaches 180, change direction to -
Whenever rotation reaches 0, change direction back to +
We track the rotation in the i variable
<!DOCTYPE html>
<html>
<head>
<title>ttt</title>
</head>
<body>
<div id="memo" style="position: fixed;margin: 140px;">
_____________
</div>
<button onclick="myfun()">Rotate</button>
<script>
let i = 0;
let direction = '+';
function myfun() {
if (i === 180) direction = '-';
if (i === 0) direction = '+';
if (i < 180 && direction === '+') {
i += 45;
} else {
i -= 45;
}
console.log(i);
document.getElementById("memo").style.transform += "rotate(" + direction + 45 + "deg)" ;
}
</script>
</body>
</html>
You need to get the rotation of element first, as variable, then you can change direction of rotation for example like this.
if(currentrotation>=180)
{
rightrotation=false
};
else if(currentrotation<=0)
{
rightrotation=true
}
if(rightrotation)
{
i+=45;
}
else
{
i-=45;
}
To get current value of rotation you need to do some math functions. I have found this website that explains it Get Rotation value of css
EDIT: #Frank Castle already posted better solution

Several rotating divs using Javascript

I need to have several divs and each of them should be able to rotate in four(!) directions independently by mouse click.
From this question (and some other) I've found pretty suitable way to rotate in 4 directions (not in two which is much easier)
Rotate a div using javascript, here is the fiddle
JS:
$(document).ready(function() {
var degree = 0; //Current rotation angle, 0->0, 1->90, 2->180, 3->270
$('.rotating').click(function() {
$(this).toggleClass('rotated' + degree.toString()); //Disable previous rotation
degree = (degree + 1) % 4;
$(this).toggleClass('rotated' + degree.toString()); //Add new rotation
});
});
But it works well only for one rotating element. As soon as I add the second div, it stops working as expected (rotations are not independent, try to click on "A" first and then on "B")
<div class="rotating rotated0">A</div>
<div class="rotating rotated0">B</div>
I assume, the root cause is because I use one "degree" variable and it's shared between my divs. So, that's the question - how can I implement several divs which can be rotated independently?
I've updated the code according to first answers (changed id to class), but initial issue with independence is still in place.
id attribute must be only one. Change id into class.
UPDATED
Here is final code:
$(document).ready(function() {
$('.rotating').click(function() {
var currentDeg = $(this).attr("data-deg");
$(this).css({ '-moz-transform': 'rotate(' + currentDeg + 'deg)'});
$(this).css({ WebkitTransform: 'rotate(' + currentDeg + 'deg)'});
currentDeg = eval(currentDeg)+eval(90);
$(this).attr("data-deg", currentDeg.toString());
//restore
if(currentDeg > 270){
$(this).attr("data-deg", "0");
}
});
});
.rotating {
width: 20px;
height: 20px;
background-color: red;
margin-top: 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="rotating" data-deg="90">A</div>
<div class="rotating" data-deg="90">A</div>
Here is your code fixed.
$(document).ready(function() {
var degree = 0; //Current rotation angle, 0->0, 1->90, 2->180, 3->270
$('.rotating').click(function() {
$(this).toggleClass('rotated' + degree.toString()); //Disable previous rotation
degree = (degree + 1) % 4;
$(this).toggleClass('rotated' + degree.toString()); //Add new rotation
});
});
Markup:
<div class="rotating">A</div>
<div class="rotating">B</div>

`queue` callback only executes once?

I have a jQuery function that loops. What I want to do is for the $bird_wing_left element to rotate 30 degrees and then rotate back to 0 degree (in an infinite loop).
$(document).ready(function() {
var rotate = 0;
setInterval(function(){
rotate = 30;
$bird_wing_left.css({ transform: "rotate(" + rotate + "deg)" }).delay(1000).queue(function(){
rotate = 0;
$(this).css({ transform: "rotate(" + rotate + "deg)" });
});
}, 3000);
});
The first time it did rotate 30 degrees, then to 0 degrees, then to 30 degrees. However, afterwards, it seems to ignore the callback (which resets the degree value to 0), hence, it just keeps on being at 30 degrees on and on.
What could be the issue?
This is the jsFiddle: https://jsfiddle.net/iamacatperson/86z26hdw/
When you queue a function, within the function you have to dequeue (or call "next", more below) to allow the queue to continue processing (as shown in the examples). Just add $(this).dequeue() within your queue callback:
var $bird_wing_left = $("#wing");
$(document).ready(function() {
var rotate = 0;
setInterval(function() {
rotate = rotate + 30;
$bird_wing_left.css({
transform: "rotate(" + rotate + "deg)"
}).delay(1000).queue(function() {
rotate = rotate - 30;
$(this).css({
transform: "rotate(" + rotate + "deg)"
}).dequeue(); // <====================
});
}, 3000);
});
body {
padding-top: 2em;
}
<div id="wing" style="width: 10em">Bird wing</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Alternately, since jQuery 1.4 the queue callback has been given an argument (traditionally called next) it can call to keep the queue going:
var $bird_wing_left = $("#wing");
$(document).ready(function() {
var rotate = 0;
setInterval(function() {
rotate = rotate + 30;
$bird_wing_left.css({
transform: "rotate(" + rotate + "deg)"
}).delay(1000).queue(function(next) { // <=====
rotate = rotate - 30;
$(this).css({
transform: "rotate(" + rotate + "deg)"
});
next(); // <=====
});
}, 3000);
});
body {
padding-top: 2em;
}
<div id="wing" style="width: 10em">Bird wing</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Side note: You can use += and -= if you like, e.g. rotate += 30; and rotate -= 30;
Quick fix could be to check rotate variable value before setting it.
if(rotate == 0)
rotate = rotate + 30;
else
rotate = 0;

Continuous rotate image onclick of button

To display Image I used colorbox..In that I have add rotate-left and rotate-right to rotate the image..
The code is:
var rotate_right = document.getElementById('cboxRight');
$(rotate_right).on('click', function () {
var cboxphoto = document.getElementsByClassName('cboxPhoto')[0].style;
cboxphoto.setAttribute('-ms-transform', 'rotate(90deg)');
});
var rotate_left = document.getElementById('cboxLeft');
$(rotate_left).on('click', function () {
var cboxphoto = document.getElementsByClassName('cboxPhoto')[0].style;
cboxphoto.setAttribute('-ms-transform', 'rotate(270deg)');
});
It rotate 90deg if I click again on rightrotate button then it wont work..I want to rotate it again when click on button
You're only ever rotating to 90 or 270 degrees. When you click again, it doesn't move as it is already rotated to that angle.
Keep track of the current rotation instead and set the attribute to that value plus or minus 90deg - you can probably clean up the code a bit as well, but something like this fiddle: http://jsfiddle.net/w6ho689e/
var degrees = 0;
$("#cboxRight").on('click', function () {
var $cboxphoto = $('.cboxPhoto');
degrees += 90;
$cboxphoto.css('-ms-transform', 'rotate(' + degrees + 'deg)');
$cboxphoto.css('-webkit-transform', 'rotate(' + degrees + 'deg)');
$cboxphoto.css('transform', 'rotate(' + degrees + 'deg)');
});
$("#cboxLeft").on('click', function () {
var $cboxphoto = $('.cboxPhoto');
degrees -= 90;
$cboxphoto.css('-ms-transform', 'rotate(' + degrees + 'deg)');
$cboxphoto.css('-webkit-transform', 'rotate(' + degrees + 'deg)');
$cboxphoto.css('transform', 'rotate(' + degrees + 'deg)');
});

Rotating on mouse move

Something I've wanted to learn for quite a time now, but haven't been able to figure out.
http://jsfiddle.net/Mobilpadde/Xt7ag/
Then you move the mouse, it follows, which is the easy part, but I want to rotate too, like always look in the direction of the mouse, but not so static, more like, if you move your mouse up, it should kinda rotate first, and then you move the mouse further away, it should begin to follow again (If you know what I mean).
Is that something simple to do, or 3k lines? (Or maybe a jQuery plugin?)
Hiya I got it something more closer by using an old post of mine : demo http://jsfiddle.net/Z3pGQ/3/
I am still working, will flick you more smoother version or if you can improve before me:
Old post: Rotating an element based on cursor position in a separate element
Hope it helps, I am trying to make it smoother now, cheers
Sample code
$(document).ready(function() {
$(document).mousemove(function(e) {
$(".firefly").css({
"top": (e.pageY * 2) + "px",
"left": (e.pageX * 2 + 130) + "px"
});
})
})
var img = $(".firefly");
if (img.length > 0) {
var offset = img.offset();
function mouse(evt) {
var center_x = (offset.left) + (img.width() / 2);
var center_y = (offset.top) + (img.height() / 2);
var mouse_x = evt.pageX;
var mouse_y = evt.pageY;
var radians = Math.atan2(mouse_x - center_x, mouse_y - center_y);
var degree = (radians * (180 / Math.PI) * -1) + 90;
img.css('-moz-transform', 'rotate(' + degree + 'deg)');
img.css('-webkit-transform', 'rotate(' + degree + 'deg)');
img.css('-o-transform', 'rotate(' + degree + 'deg)');
img.css('-ms-transform', 'rotate(' + degree + 'deg)');
}
$(document).mousemove(mouse);
}​
Image
This is going to involve a lot more math than I want to do right now, but you can apply rotations with css easily. Here are the properties for mozilla and webkit, you can see the rest of the (IE,Opera...) at this page. Here is your function with a 120deg rotation applied. You will still need to calculate the proper rotation, and adjust the left and top accordingly.
$(document).mousemove(function(e){
$(".firefly").css({
"top":(e.pageY*2)+"px",
"left":(e.pageX*2+130)+"px",
"-moz-transform": "rotate(120deg)",
"-webkit-transform": "rotate(120deg)"});
})
There is a jQuery plugin for that http://pixelscommander.com/en/iphone-development/rotate-html-elements-with-mouse/

Categories

Resources