Reputation: 31
Is it possible to fix an image src set by a javascript function and returned to a HTML tag.
I have a set of array objects that includes, amongst other details, the location of an image for each object:
Person[1]= {
Image:"Adam.jpg",
Name:"Adam"
};
I then have a function that is designed to extract the relevant image dependent upon an index sent to it.
function SetImage(DeskNo)
{
document.getElementById("DeskImage").src=Person[1].Image
}
This is where I run into problems. The block:
<div class="img>
<script>
SetImage(1);
</script>
<img id="DeskImage" width="30" height="30">
doesn't display anything, but does appear to very briefly flash up an image on loading before clearing it.
This block is repeated, but with an index of 2 and then 3 etc. The idea is that the function can be used to extract and return the image, and display several of them on screen at the same time.
A similar function triggered by 'onmouseover' seems to work successfully, which makes me wonder if the image is being overwritten somewhere, which brings me to my question title. Is it possible to set an src via an element id (in this case 'DeskImage') or otherwise and fix it after the image has been set the first time, even if the src that id points to changes?
I wondered if a direct return of the src from the function may be possible, or alternatively if the index can be automatically appended to the id, however I couldn't identify anything in my searches.
If anyone has any ideas they would be appreciated.
Upvotes: 3
Views: 93
Reputation: 227260
The problem is you are calling SetImage
before DeskImage
exists. You need to wait until the page is ready before calling your script.
<script>
window.onload = function(){
SetImage(1);
};
</script>
<img id="DeskImage" width="30" height="30">
Upvotes: 1