Variable for img src=

Lee Palmer picture Lee Palmer · Apr 20, 2009 · Viewed 64.9k times · Source

I have a question. Firstly, I am not going to pretend that I know what I am talking about here. I am a newbie to http and JavaScript.

I think my question may be answered in this post IMG SRC tags and JavaScript but I thought I would explain the exact thing I am trying to achieve in case there is an easier way.

I have a webpage, I want to display an image on it. Only thing is, the image is coming from an automated system monitor, the image is automatically generated each day and placed in a new directory depending on date.

e.g. On April 4 = "http://host/partition/2009/apr/04/cpu.gif"
e.g. On April 5 = "http://host/partition/2009/apr/05/cpu.gif"

To facilitate this, I have created some basic JavaScript to give me the date in the format I need it. I have all that working. Now I just want to use that variable I created to show the image. I have the JavaScript code stored in a function called displaydate() If I do this <script language="JavaScript"> displaydate() </script> I see "http://host/partition/2009/apr/05/cpu.gif" and that is correct.

Now how do I display this on the site correctly?

 <a href="displaydate()"><img src="displaydate()" </a></td>    //This does not work. I am just adding it to show where I have been heading.

P.S. I have read a lot of pages on this and been trying a lot of things, but have had no luck so far. Any help, would be much appreciated.

Answer

Brett Bender picture Brett Bender · Apr 20, 2009

Yes, that page probably does answer your question. Basically, you want this javascript:

<script type="text/javascript">
document.getElementById('image').src = "yourpicture.png";
</script>

Except you want to replace the "yourpicture.png" with the function you wrote to generate the correct path to the image on disk, so...

<script type="text/javascript">
document.getElementById('image').src = displaydate();
</script>

Of course, you might need to modify this a bit for your own uses, the getElementById will take as an argument whatever the id attribute of your < img > tag is. You probably want to execute the above javascript after your page has loaded, i.e.:

<html>
<head>
<script type="text/javascript">
function load()
{
document.getElementById('image').src = displaydate();
}

function displaydate()
{
//your displaydate() function here
}
</script>
</head>

<body onload="load()">

<img src="nothing.jpg" id="image" name="image"/>
</body>
</html>