Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

JavaScript to change an image's src

Status
Not open for further replies.

dakota81

Technical User
May 15, 2001
1,691
0
0
US
If I've got an image listed as (for example):

<img src=&quot;image1.gif&quot; name=&quot;image1&quot;>

Then I can change that image with an event such as (for example):

<a href=&quot;...&quot; onmouseover=&quot;document.images.button1.src='image2.gif'&quot;>


However I am stuck trying to get a general function to sit in the page's head section that I can pass in as strings the image name and the new src field. I know there's a way because I see a similar example in a book I'm working from, but I can't quite get the syntax or whatever. Any help?
 
Try this...

It wil work in all browsers too...


<script language=&quot;JavaScript&quot;>

if (document.images){
imgr1 = new Image()
imgr1.src = &quot;image1.gif&quot;
imgr2 = new Image()
imgr2.src = &quot;image2.gif&quot;
}

</script><a href=&quot;xyz.htm&quot; onMouseOver=&quot;if(document.images) { imgr.src =imgr2.src }&quot;
onMouseOut=&quot;if(document.images) {imgr.src =imgr1.src}&quot;>
<img border=&quot;0&quot; src=&quot;image1.gif&quot; width=&quot;69&quot; height=&quot;23&quot; name=&quot;imgr&quot; border=&quot;0&quot;>
</a>


Hope it works...else let me know...

Bye,

Tomm :)
 
You could simply do :

<img src=offSrc.png
onMouseOver=&quot;this.src='onSrc.png'&quot;
onMouseOut=&quot;this.src='offSrc.png'&quot;
onClick=&quot;location.href='myUrl.html'&quot;>

Gary Haran
 
I can already replace the image like you guys are showing - but I want to to expand a little more in what I can do, and doing so I'd like to know if there's a function that can be used to change the image - such as:

function(imageName, imageSRC) {
...


I'm sure there is a way, but I just can't get the syntax correct.
 
how about with an id (forget about name)?


<img src=off.png id=myImage>

<script>
function getElement(id)
{
return (document.all) ? document.all[id] : document.getElementById(id) ;
}
function changeSrc(id, src)
{
var image = getElement(id);
if(image)
{
image.src = src;
}
}

changeSrc('myImage', 'onSrc.png')
</script>

Hope this helps. Gary Haran
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top