Cbenn Cbenn - 7 months ago 110
Javascript Question

Rotate and unrotate an image onClick with javascript

I have been trying to find how to make an image rotate 90 degrees to the right on the first click, and when clicked again, return to it's original orientation.
I was looking at this question made by another person on stack overflow, but this didn't include the image rotating back when it was clicked again.

So far, CSS has shown potential, but I cannot seem to get the image rotated back on the second click.

This is the image if you need a reference:
image

Here is my script:

<html>
<head>
<style>
.rotate {
-ms-transform: rotate(90deg);
-webkit-transform: rotate(90deg);
transform: rotate(90deg);
}

.normal {
-ms-transform: rotate(0deg);
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
</style>

<script>
function Rotate() {
var rotate = 0
var rotate = rotate + 1
if (rotate = 2) {
document.getElementbyID(image).className = 'normal';
}
else if (rotate <= 3) {
var rotate = 0
location.reload();
}
else {
document.getElementbyID(image).className = 'rotate';
}
}
</script>


</head>
<body>

<img src="http://i.stack.imgur.com/IAY0q.png" alt="image" onclick="Rotate()" class="normal" id="image"/>

</body>
</html>

Answer

Here is a snippet running what you ar trying to achieve:

function Rotate() {
		var element = document.getElementById('image');

		if (element.className === "normal") {
			element.className = "rotate";
		}
		else if ( element.className === "rotate") {
			element.className = 'normal';
		}
	}
.rotate {
   -ms-transform: rotate(90deg);
    -webkit-transform: rotate(90deg);
     transform: rotate(90deg);
}

.normal {
   -ms-transform: rotate(0deg);
    -webkit-transform: rotate(0deg);
     transform: rotate(0deg);
}
<html>
<head>
</head>
<body>

<img src="http://i.stack.imgur.com/IAY0q.png" alt="image" onclick="Rotate()" class="normal" id="image"/>

</body>
</html>

Keep in mind that you had several syntax errors on your code such as: document.getElementById() and using a single = for comparison.

You can check you browser console for checking erros like those.