/    Sign up×
Community /Pin to ProfileBookmark

onClick Swap Image & onClick restore Image

Hi is there a simpel function for swapping an image onClick. And then when the image is swapped and you Click on the same item it restores again.

Thanks in advance

to post a comment
JavaScript

10 Comments(s)

Copy linkTweet thisAlerts:
@JPnycFeb 22.2005 — Try searching here 1st. That's been answered and code posted countless times.
Copy linkTweet thisAlerts:
@KorFeb 23.2005 — one variant, use a parameter

var q=0;

function swapImg(){

if(q==0){

[i]reference.element[/i].setAttribute('src','newImage.jpg');

q++;

}

else{

[i]reference.element[/i].setAttribute('src','oldImage.jpg');

q--;

}

}
Copy linkTweet thisAlerts:
@zebdaagauthorMar 07.2005 — i looked at the code and search the forum but couldn't find anything that worked. this is with what I ended


[code=php]
<body bgcolor="#999999">
<script>
var q=0;
function swapImg (imgName)
{
if(q==0){
document.images[imgName].src = eval('imgName + ".jpg"')
q++
}
else{
document.images[imgName].src = eval('imgName + ".gif"')
q--
}
</script>
<a href="javascript:swapImg('01')"><img src="img/01.gif" name="contact" width="700" height="359"></a>
</body>[/code]
Copy linkTweet thisAlerts:
@KorMar 08.2005 — Try this:
[code=php]
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script language="JavaScript" type="text/JavaScript">
var q=0;
var root='img/';
function swapImg(ima){
nr = ima.getAttribute('src').split('/');
nr = nr[nr.length-1].split('.')[0];
if(q==0){ima.setAttribute('src',root+nr+'.jpg');q++;}
else{ima.setAttribute('src',root+nr+'.gif');q--;}
}
</script>
</head>
<body>
<img style="cursor:pointer" src="img/01.gif" name="contact" width="700" height="359" onclick="swapImg(this)">
</body>
</html>
[/code]
Copy linkTweet thisAlerts:
@jonwinterNov 01.2006 — I noticed you gave an excellent piece of code for swapping images and I've tried to use this myself for something. I'm trying to create a traffic light system where different systems we have can be shown as either red, amber or green.

I wanted to use a three images for each system, which represent the traffic lights. What I need them to do is if you click on an image it changes to another version i.e. maybe from looking off to looking on. Also, if any of the images for that system are already shown as an 'on' state, they change to an 'off' state i.e. it was originally green and you now select amber.

I have about 20 systems and just cannot get the script to work for each one! Can you help...?

Cheers

Jon
Copy linkTweet thisAlerts:
@asllearnerNov 13.2007 — another version

this creates an array...no need to hassle with gif vs jpg, just use full names...

then toggles (2 pics) (could be used to cycle through multiple images...make the 0 and 1 into variable index, just keep adding one to the index and test for out of bounds (>namesVec.length) )

...you have to keep track of the index, naturally...

[CODE]
var namesVec = new Array("myfirstimage.gif", "secondimage.jpg");
var root='theme_images/';
function swapImg(ima){
// divides the path
nr = ima.getAttribute('src').split('/');
// gets the last part of path, ie name
nr = nr[nr.length-1]
// former was .split('.')[0];

if(nr==namesVec[0]){ima.setAttribute('src',root+namesVec[1]);}
else{ima.setAttribute('src',root+namesVec[0]);}

}
[/CODE]
Copy linkTweet thisAlerts:
@greed83Feb 07.2008 — I will asume that you call the function with a onclick="swapImg();" ? I cannot get this to work for the life of me. Very simple but EXTREMLY frustrating lol! This is what i have. I must be missing soemthing very very simple....

[CODE]

//___________________________________________________________
// Swap Image Script ________________________________________
//___________________________________________________________

var namesVec = new Array("switch_off.gif", "switch_on.gif");
var root ='images/';
function swapImg(ima){
// divides the path
nr = ima.getAttribute('src').split('/');
// gets the last part of path, ie name
nr = nr[nr.length-1]
// former was .split('.')[0];

if(nr==namesVec[0]){ima.setAttribute('src',root+namesVec[1]);}
else{ima.setAttribute('src',root+namesVec[0]);}

}

[/CODE]


[code=html]
<img src="images/switch_off.gif" width="150" height="229" border="0" onclick="swapImg();" />
[/code]


Any help would be great!

Cheers,

G
Copy linkTweet thisAlerts:
@asllearnerFeb 07.2008 — I am not a programmer, but a hunt and peck amateur, and I did this a long time ago, and for reasons I don't fully recall, I ended up with the following, which I am posting in its entirety rather than editing down, to prevent me making an error, which may or may not help you....it looks identical to your code...except....

[CODE]
var namesVec = new Array("arrowdcrimsonright.gif", "arrowdcrimsondown.gif");
var root='theme_images/';

function togglepics(image,showorhide){
if (showorhide=="show") {image.setAttribute('src',root+namesVec[0]);}
if (showorhide=="hide") {image.setAttribute('src',root+namesVec[1]);}

nr = image.getAttribute('src').split('/');
nr = nr[nr.length-1]

if(nr==namesVec[0]){image.setAttribute('src',root+namesVec[1]);}
else{image.setAttribute('src',root+namesVec[0]);}

}[/CODE]


Now, the following paragraph is a tangent, but I add it for explanation. read it but the answer to your question is not contained therein, but below...

I am pretty sure you may be able to ignore my first two if statements...if I recall correctly I called this function in special links sometimes from another function that shows or hide all the images (the image appears in many elements) on the page, and I use this function to do double duty as a shower or hider...I use showorhide ="show" if I want to use the function as part of another function to set all the images to the second image (which I am calling show because it is a part of a function that shows descriptons) and likewise for hiding, showorhide="hide"....

ok, seems totally irrelevant, but...

as to your question, that being said, when I show or hide an individual image, I pass a nonsense value of 0 as showorhide, so the first ifs are ignored.......also, my calls are from a button, and so I use a firstchild reference to call them, so...here is an example call...

[CODE]
<button
class="button"
onclick="togglepics(this.firstChild, 0)"><img src="./theme_images/arrowdcrimsonright.gif" height="14"></button>[/CODE]


Which leads to:

I think if you call directly with togglepics(this) from the image element, it should work??? he said with fingers crossed, remove the second argument, and the first two if statements...good luck compadre...

ps if you use the firstchild method, I found out the hard way that god knows why there must not be a space or anything at all between the button and the image...buyer beware.
Copy linkTweet thisAlerts:
@greed83Feb 08.2008 — This is so aggravating. It seems no matter what script i try, no matter how i try it, this will not work. Thanks for the reply though but still, that will not work for some reason.
Copy linkTweet thisAlerts:
@Messier111Sep 12.2008 — 

[code=html]
<img src="images/switch_off.gif" width="150" height="229" border="0" onclick="swapImg();" />
[/code]


Any help would be great!

Cheers,

G[/QUOTE]


Hello !

Your code works very well for me, but in the HTML you must use
[code=html]onclick="swapImg(this)"[/code] instead of [code=html]onclick="swapImg();"[/code]

Best regards
×

Success!

Help @zebdaag spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.28,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...