Switch img on img click

javascript
function changePic(el, pic1, pic2) {
var pic=((el.src.match(pic1)!=null)? pic2 : pic1);
el.src="images/"+pic+".jpg";
}
window.onload=function() {
var pic=document.getElementById('drink');
pic.onclick=function(){changePic(this,'wine','beer');}
}
HTML
<h1>Switch img on img click</h1>
<p><img id="drink" src="images/wine.jpg" alt=""></p>

Comments

#1
2007-11-18 Lilly says :

Hi,

I am building family website for my grandfather and I am somewhat struggling at the moment on switching images...I am trying to work with your code but it is hard for me to understand...this is what I have so far:

<html>
<head>
<title>Image switch</title>
<script language="Javascript">

function changePic(el, pic1, pic2)
{
var pic=((el.src.match(pic1)!=null)? pic2 : pic1);
el.src="images/"+pic+".jpg";
}
window.onload=function() {
var pic=document.getElementById('drink');
pic.onclick=function(){changePic(this,'wine','beer');}
}


</script>
</head>
<body>


<p><img id="drink" src="http://officeblogs.net/powerpoint/PictureLayoutDefault.png" alt=""></p>
<p><img id="wine" src="http://www.sunflowerhead.com/msimages/PictureStyles.png" alt=""></p>

</body>
</html>

#2
2009-10-15 DJ says :

Freakin' sweet. That's grand. I've been trying to figured out how to do that effectively for a week now for a project my boss has me doing. This is probably saving my job. Haha. Thank you much.

#3
2009-10-15 BonRouge says :

DJ,
Nice one. Glad it helped.
Thanks for the feedback. smile

Comment form

Please type the word 'sake' here:

BB code available :

  • [b]...[/b] : bold
  • [it]...[/it] : italic
  • [q]...[/q] : quote
  • [c]...[/c] : code
  • [url=...]...[/url] : url