Changing IMG SRC with Javascript

Carriag picture Carriag · Sep 8, 2009 · Viewed 75.8k times · Source

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!

Answer

JasonWoof picture JasonWoof · Sep 8, 2009

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)