views:

3261

answers:

3

I'm new at javascript and while there are many more complex solutions, I don't understand them and hope I don't have to at this point.

I have a main picture...

<img src="main-picture.jpg" name="Mainpic" id="image">

...and I want to be able to change this picture when I click on one of two thumbnails.

<a href="" onclick="FirstPic()"><img src="replacement1.jpg" name="pic1"></a>
<a href="" onclick="SecPic()"><img src="replacement2.jpg" name="pic2"></a>

My javascript code I thought would be super easy. I'm currently using...

function FirstPic(){
     document.Mainpic.src = document.pic1.src
     return
    }

function SecPic(){
     document.Mainpic.src = document.pic2.src
     return
    }

Now the variable is changing however it's not staying changed. When the thumbnail is clicked on, the replacement picture flashes on the screen and then it returns to the original main-picture.jpg.

How do I make the change permanent until a different thumbnail is clicked?

Thanks!

+4  A: 

I think it's flipping back because your page is reloading.

You need to return false from your onclick= if you don't want the href= value to activate after your onclick.

Also, you can set href="#" just in case. # goes nowhere (doesn't ever reload the page)

JasonWoof
On other note, I think you can do away with link tag and write the click event on the image itself.
Biswanath
JasonWoof, that worked perfect, thanks. However Biswanath's answer worked perfect too and was more efficient so I just got rid of the link tag altogether.
A: 

I think your page is refreshing by your click, change your links as :

<a href="" onclick="FirstPic(); return false;"><img src="replacement1.jpg" name="pic1"></a>
<a href="" onclick="SecPic(); return false;"><img src="replacement2.jpg" name="pic2"></a>
Canavar
A: 

Why not do something like this (haven't checked the syntax completly, so it could be faulty.

function FirstPic()
{
    var pic1 = document.getElementById("pic1"); 
    if (pic1 == typeof('undefined')) return;
    pic1.src = "newpicname.jpg";
}

Make sure you give the tags an ID attribute called pic1 and pic2 (instead of a name attribute) and give the image itself an 'onclick' attribute...

<img onclick='FirstPic()' id='pic1' src='image1.jpg' />
Wim Haanstra