I have 4 images in an HTML page: 1.png, 2.png, 3.png and 4.png. When the user moves the mouse pointer over to 1.png, 2.png should replace 4.png. Similarly, if the mouse pointer goes to 2.png, 3.png should be replaced with 1.png.
Here's my code:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript">
function image1_mouseover()
{
var img2 = document.getElementById('img2');
var img4 = document.getElementById('img4');
img2.setAttribute('src','exercice1/4.png');
img2.setAttribute('id','img4');
img4.setAttribute('src','exercice1/2.png');
img4.setAttribute('id','img2');
}
function image2_mouseover()
{
var img1 = document.getElementById('img1');
var img3 = document.getElementById('img3');
img1.setAttribute('src','exercice1/3.png');
img1.setAttribute('id','img3');
img3.setAttribute('src','exercice1/1.png');
img3.setAttribute('id','img1');
}
function image3_click()
{
}
</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" onmouseover="image1_mouseover()"></td>
<td><img src="exercice1/2.png" alt="Image 2" id="img2" onmouseover="image2_mouseover()"></td>
</tr>
<tr>
<td><img src="exercice1/3.png" alt="Image 3" id="img3"></td>
<td><img src="exercice1/4.png" alt="Image 4" id="img4"></td>
</tr>
</table>
</body>
</html>
It works at first when I move the mouse to 1.png and 2.png replaces 4.png. But then when I move the mouse to 2.png, 1.png doesn't replace 3.png, instead I had to move the mouse over 4.png for that to happen.
What's wrong?
I think you're confused over what is happening to the images.
Instead of switching their attributes, how about switching the images' positions?
Then use this HTML: