Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
93
rated 0 times [  94] [ 1]  / answers: 1 / hits: 90042  / 14 Years ago, mon, december 6, 2010, 12:00:00

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


More From » javascript

 Answers
11

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()/>

[#94716] Friday, December 3, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
janeth

Total Points: 498
Total Questions: 91
Total Answers: 89

Location: Malaysia
Member since Wed, May 11, 2022
2 Years ago
;