# [SOLVED] Use Javascript Variable as HTML Image Source



## sbussy89

I declare an image in some script in html like this:

myimage = New Image
myimage.src = "image\source.jpg"

I want to use the source of this image as a variable in an html image, like this:

<img src=myimage.src name="image" onMouseOver="image.src=new.src" onMouseOut="image.src=old.src">

but the "src=myimage.src" does not work. Is there any way I can do this?


----------



## jamiemac2005

*Re: Use Javascript Variable as HTML Image Source*

it doesn't work because the browser does not parse the src attribute as containing javascript. Something like this might work:



Code:


<img  src="javascript: this.src=myimage.src" name="image" onMouseOver="image.src=new.src" onMouseOut="image.src=old.src">

but you'd be better to do this:



Code:


<img  src="" name="image" onMouseOver="image.src=new.src" onMouseOut="image.src=old.src" onload="this.src=myimage.src">

Because then you know the image has loaded etc. and it is better practice than putting javascript in the src attribute.

Cheers,
Jamey


----------



## sbussy89

*Re: Use Javascript Variable as HTML Image Source*

unfortunately neither of those worked, they both came up with the empty box logo for the initial image load, but the mouseOvers still worked. thanks for the advice, ill keep looking


----------



## sbussy89

*Re: Use Javascript Variable as HTML Image Source*

update - in the javascript, where i set the value of the string, i tried instead this...

document.image.src = myimage.src
or
document.getElementByID("image").src = myImage.src

but neither worked, it just overrode what source I set in the javascript with the source given in the image tag, even when I left the source parameter out of the tag (thus giving it an invalid path)


----------



## sbussy89

*Re: Use Javascript Variable as HTML Image Source*

fixed!!!! put the javascript from the last post directly after each image tag


----------



## jamiemac2005

Okay, glad you've got it sorted.

Cheers,
Jamey


----------

