How to Swap images using Javascript


In this tutorial,I show you how to swap images using javascript. for example,when you click on one image, it get changed with another image.In other words, Images interchaged  positions.


Steps to Swap images : 


  • Create a new file and paste following code,save it as swap.html.



<html>

<title>
Swap
</title>
<head>
<script>
var q=0;
function swapImage(){
if(q==0){
document.getElementById("first1").setAttribute('src','imga.jpg');
document.getElementById("first").setAttribute('src','imgb.jpg');
document.getElementById("third").setAttribute('src','imgd.jpg');
q++;
}
else{
document.getElementById("first1").setAttribute('src','imgb.jpg');
document.getElementById("first").setAttribute('src','imga.jpg');
q--
}
}
var m=0;
function swapImage1(){
if(m==0){
document.getElementById("first1").setAttribute('src','imgc.jpg');
document.getElementById("second").setAttribute('src','imgb.jpg');
document.getElementById("first").setAttribute('src','imga.jpg');
m++;
}
else
{
document.getElementById("first1").setAttribute('src','imgb.jpg');
document.getElementById("second").setAttribute('src','imgc.jpg');
m--
}
}
var l=0;
function swapImage2(){
if(l==0){
document.getElementById("first1").setAttribute('src','imgd.jpg');
document.getElementById("third").setAttribute('src','imgb.jpg');
document.getElementById("second").setAttribute('src','imgc.jpg');
l++;
}
else
{
document.getElementById("first1").setAttribute('src','imgb.jpg');
document.getElementById("third").setAttribute('src','imgd.jpg');
l--
}
}
</script>
</head>
<body>
    <p align="center">
   <img id="first" src="imga.jpg"  height="200px" width="200px" onclick="swapImage();" border="0" />
<img id="second" src="imgc.jpg"  height="200px" width="200px"onclick="swapImage1();" border="0" />
<img id="third" src="imgd.jpg"  height="200px" width="200px"onclick="swapImage2();" border="0" /><br></p>
<p align="center">
<img id="first1" src="imgb.jpg"  height="400px" width="620px"  border="0"/></p> 
</body>
</html>



Rate this posting:
{[['']]}

1 comment:

Powered by Blogger.