Reputation: 2084
I have 4 images in an HTML page: 1.png, 2.png, 3.png and 4.png. I want when the user click in the image 3, a rotation to the right of the various images is performed. (replace the image 1 with image 3, image 2 by image 1,image 4 by image 2 and image 3 by image 4).
this is the code I tried, but It won't work :
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript">
function rotation()
{
img1 = document.getElementById('img1');
img2 = document.getElementById('img2');
img3 = document.getElementById('img3');
img4 = document.getElementById('img4');
img2.parentNode.appendChild(img4);
img1.parentNode.appendChild(img2);
img3.parentNode.appendChild(img1);
img4.parentNode.appendChild(img3);
}
</script>
<style type="text/css">
table
{
margin-left:auto;
margin-right:auto;
}
</style>
</head>
<body>
<table class="centrer">
<tr>
<td><img src="exercice1/1.png" alt="Image 1" id="img1"></td>
<td><img src="exercice1/2.png" alt="Image 2" id="img2"></td>
</tr>
<tr>
<td><img src="exercice1/3.png" alt="Image 3" id="img3" onclick="rotation()"></td>
<td><img src="exercice1/4.png" alt="Image 4" id="img4"></td>
</tr>
</table>
</body>
</html>
The problem is when I click for the first time on image 3 the images are ordered like this:
2
1 3 4
and in the second time they ordred like this:
2 1 3 4
and I want them to be ordered like this:
before rotation:
1 2
3 4
after rotation :
3 1
4 2
Upvotes: 0
Views: 130
Reputation: 5742
And what is happening instead? My guess is that the parentNode of the elements are changing when you move them:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript">
function rotation()
{
var img1 = document.getElementById('img1'),
img2 = document.getElementById('img2'),
img3 = document.getElementById('img3'),
img4 = document.getElementById('img4'),
cont1 = img1.parentNode,
cont2 = img2.parentNode,
cont3 = img3.parentNode,
cont4 = img4.parentNode;
cont2.appendChild(img4);
cont1.appendChild(img2);
cont3.appendChild(img1);
cont4.appendChild(img3);
}
</script>
<style type="text/css">
table
{
margin-left:auto;
margin-right:auto;
}
</style>
</head>
<body>
<table class="centrer">
<tr>
<td><img src="exercice1/1.png" alt="Image 1" id="img1"></td>
<td><img src="exercice1/2.png" alt="Image 2" id="img2"></td>
</tr>
<tr>
<td><img src="exercice1/3.png" alt="Image 3" id="img3" onclick="rotation()"></td>
<td><img src="exercice1/4.png" alt="Image 4" id="img4"></td>
</tr>
</table>
</body>
</html>
Upvotes: 0
Reputation: 13476
Change the src
attribute instead. Like so:
function rotation()
{
img1 = document.getElementById('img1');
img2 = document.getElementById('img2');
img3 = document.getElementById('img3');
img4 = document.getElementById('img4');
src1 = img1.src;
src2 = img2.src;
src3 = img3.src;
src4 = img4.src;
img2.src = src4;
img1.src = src2;
img3.src = src1;
img4.src = src3;
}
Upvotes: 1