Skip to content Skip to sidebar Skip to footer

Javascript Simple Onclick Image Swap

I am trying to use Javascript to swap an image, so far I can get it from A to B, but not back. Here is what I'm using to create one swap:

Solution 1:

Try this simple trick... easy to maintain.

<script>var onImg= "on.jpg";
var offImg= "off.jpg";
</script><imgsrc="on.jpg"onclick="this.src = this.src == offImg ? onImg : offImg;"/>

Solution 2:

In your code the problem is when you alert window.document.pic.src its print like http://localhost/pic1.png and then you are are use condition if (window.document.pic.src == 'pic1.png') how is it true. try this

<scripttype="text/javascript">functiontest()
{
    alert(window.document.pic.src);
     //alert msg print like http://localhost/test/pic1.pngif (document.pic.src=='http://localhost/test/pic1.png'){

document.pic.src='pic2.png';
} 
elseif (document.pic.src=='http://localhost/test/pic2.png'){

document.pic.src='pic1.png';
}
}
</script><imgsrc="pic1.png"name="pic"onclick="test()"/>

Solution 3:

wrong use of == in if condition

if (window.document.pic.src == 'pic1.png'){
window.document.pic.src='pic2.png';
} 
elseif (window.document.pic.src =='pic2.png'){
window.document.pic.src='pic1.png';
}"/>

Solution 4:

  1. window.document.pic.src='pic1.png' assigns pic1.png to the left hand side. It does NOT compare.

  2. Though not directly relevant, try not to access elements by their name globally. Use their id.

  3. Your javascript should not be inside the onclick. It should be inside a javasctipt function

Combined:

The img tag:

<img src="pic1.png" name="pic"id="pic" onclick="swap()"/>

The javascript

<script>functionswap()
{
   if (document.getElementById("pic").src.endsWith('pic1.png') != -1)  //==:Comparison
   { 
      document.getElementById("pic").src = "pic2.png"; //=:assignment   
   } 
   elseif (window.document.pic.src.endsWith('pic2.png') != -1) 
   { 
      document.getElementById("pic").src = "pic1.png"; 
   }
}
</script>

Solution 5:

Your code is doing what the below lines do, it's not going inside an if else block, so if you remove your if else block the code still will work, because on mouse click it sets the value of src as 'pic2.png', which was 'pic1.png' earlier, and when you click again because it's already pic2.png so it remains the same.

<html><head><scripttype="text/javascript">functionswap() {
    window.document.pic.src='pic2.png';
}
</script></head><body><imgsrc="pic1.png"name="pic"onclick="swap()"></body></html>

Post a Comment for "Javascript Simple Onclick Image Swap"