Changing IMG SRC with Javascript

I am new to javascript, and although there are many more complex solutions, I do not understand them and hope that I do not need at this point.

I have a basic picture ...

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

... and I want to be able to change this image 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 very easy. I am 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 , but it has not remained changed. When a thumbnail is pressed, a replacement picture blinks on the screen, and then returns to the original main image .jpg.

How to make a change permanent until another thumbnail is clicked?

Thanks!

+6
javascript variables image src
source share
3 answers

I think it leans back because your page is reloading.

You need to return false from your onclick = if you do not want the href = value to be activated after your onclick.

Alternatively, you can set href = "#" just in case. # no good (never reload the page)

+6
source share

I think your page refreshes 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> 
0
source share

Why not do something like this (don't check the syntax completely, so it may 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 the name attribute) and give yourself the onclick attribute ...

 <img onclick='FirstPic()' id='pic1' src='image1.jpg' /> 
0
source share

All Articles