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 SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Javascript in an img tag 1

Status
Not open for further replies.

Pleximus

Programmer
Jul 21, 2003
7
0
0
US
I need to insert a JavaScript variable into an img src attribute, something like:

<img src=&quot;images/&quot; + JavaScript variable + &quot;/imagename.gif&quot;>

Can this be done?

Pleximus
 
hmm, don't think that will work. This may

<script>
function loadImg(){
document.myImg.src = &quot;images/&quot; + JavaScript variable + &quot;/imagename.gif&quot;
}
</script>

<body onLoad=&quot;loadImg()&quot;>
<img name=&quot;myImg&quot;>

ANOTHER OPTION - not so sure of this one:

<img name=&quot;myImg&quot; src=&quot;stockImg.jpg&quot; onLoad=&quot;document.myImg.src=&quot;&quot;images/&quot; + jsVar + &quot;/imagename.gif&quot;&quot;&quot;>


Programming today is a race between software engineers striving to build better and bigger idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning. - Rick Cook
 
<script>document.write('<img src=&quot;images/&quot;'+ $variable +'&quot;/imagename.gif&quot;>');</script>
 
mwolf00,

thanks. The onLoad method actually works... however, in IE 5 on a pc the page continues to try and load something - the image source I think - indefinitely, like its caught in some kind of loop, strange.
 
stormbind,

I am trying to avaid having to write the whole img tag with JS, hopefully i can simply insert the variable in some sort of short-hand JS manner...

thnx
 
I agree with stormbind...you probably want to keep it simple and minimize the number of function calls. It helps to make the code more readable.

Also, the more functions that are put into the &quot;onLoad()&quot; event...the slower the page loads. :( - sad, but true.
 
have a 1 pixel img in as the base img in the IMG tag so it loads immediately - then the onLoad will fire.

Programming today is a race between software engineers striving to build better and bigger idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning. - Rick Cook
 
Ok, I got it... here it is and it works:

<img name=&quot;myImg&quot; src=&quot;javascript:document.myImg.src='assets/' + variable + '/imagename.gif'&quot;>

Thanks all!

Plex
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top