Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript simple onclick image swap

Tags:

javascript

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:

<img src="pic1.png" name="pic" onclick="window.document.pic.src='pic2.png';"/>

This swaps image 1 to image 2, simple enough. But I want to be able to revert back to image 1 by clicking on the new image 2. I tried using this:

<img src="pic1.png" name="pic" onclick="
if (window.document.pic.src='pic1.png'){
window.document.pic.src='pic2.png';
} 
else if (window.document.pic.src='pic2.png'){
window.document.pic.src='pic1.png';
}"/>

It doesn't seem to work in this instance. It will switch to pic2, but not switch back to pic1. Is it something to do with onclick? My if statements? Thanks

like image 918
user339946 Avatar asked Dec 09 '22 12:12

user339946


2 Answers

Try this simple trick... easy to maintain.

<script>
var onImg= "on.jpg";
var offImg= "off.jpg";
</script>
<img src="on.jpg" onclick="this.src = this.src == offImg ? onImg : offImg;"/>
like image 123
Ed Haack Avatar answered Jan 01 '23 21:01

Ed Haack


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

<script type="text/javascript">
function test()
{
    alert(window.document.pic.src);
     //alert msg print like http://localhost/test/pic1.png
    if (document.pic.src=='http://localhost/test/pic1.png'){

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

document.pic.src='pic1.png';
}
}
</script>
<img src="pic1.png" name="pic" onclick="test()"/>
like image 24
Bhanu Prakash Pandey Avatar answered Jan 01 '23 21:01

Bhanu Prakash Pandey