View Full Version : how to embed JS variable in img src attribute?

05-16-2006, 03:26 PM

I have an external javascript file with the following code:
loct = document.location
str = new String(loct);
lind = str.lastIndexOf("/" );
burl = str.substring(0,lind);
iurl = burl + "/imagefolder/"
alert("the image url is " + iurl);

What this does:
It gets the local html file location (eg. file:///x:/path/tomy/htmlfile.html), removes the file name and appends "/imagefolder/" string to it to give the image files folder location (eg. file:///x:/path/tomy/imagefolder/). Alert() is for debugging purposes.

In the html file, I have put the script src
Now, I want to embed javascript in the src attribute of the Image like:
<img src="&{iurl};ImageFile.gif" border=0>

On opening the html file, the alert comes out properly, but the image is not shown, eventhough the "ImageFile.gif" is in its mentioned location. I have tried both in firefox 1.5 and IE 6. Where have I gone wrong?

Thanks for any directions.

05-16-2006, 04:52 PM
To create/change elements/attributes you need methods. Methods are usually nested in functions, functions are triggerend by events. This is the way javscript works. It is a dynamic language, if you know already another language, a server-side one, you should not use the same static pattern in thinking javascript code.

<img onload="this.src=iurl+'mageFile.gif'">

make sure your iurl variable is a global one.

05-17-2006, 03:21 AM
Thanks for the reply, but I was trying this method after reading the following link:
"Using JavaScript expressions as HTML attribute values": http://wp.netscape.com/eng/mozilla/3.0/handbook/javascript/getstart.htm#1016301

Is it possible to make it work as shown in the above link?

Meanwhile I will try your method also, but for my purposes, the method given in the link is highly suited. I wish I could make it work.

05-17-2006, 07:19 AM
It should work, based on your piece of code. My question is which is the event to change the src attribute? In other words, which is the action of the user which should do that change?

05-17-2006, 04:06 PM
According to the example given in the page I mentioned, there need not be any trigger to run the code. I also tried your method, it also didn't work. I checked again - javascript is enabled in my browser (getting the alert dialog I have inserted), the image is in the mentioned location (I've put the absolute path directly without javascript and it is shown). What more should I do? Thanks for any advice you might give.