tags:

views:

44

answers:

3

When my document loads, I'd like to have JavaScript reload my images' sources. To do so, I got the following code in my HTML document:

<img src="#" id="mypic" onload="reloadImage(this);"/>

and in my JavaScript document:

function reloadImage(imageElement) {
    imageElement.src = "http://www.somedomain.com/image.png";
}

However, this doesn't work. Am I using this incorrectly, or does the problem lie elsewhere?

+4  A: 

The syntax you use is correct in principle. The problem is that for the URL #, being an invalid image URL, the load event is probably never fired.

Pekka
You're right! If I replace the `#` with a valid image URL, it works as expected.
@ryyst all right! However, this will create an endless loop of `load` events and image reloads. Are you sure this is what you want?
Pekka
Oh, I thought the `onload` function would only get called when the entire document gets loaded for the first time...JavaScript is very new for me, so I guess I'll have to read up on this.
@ryyst the document's `onload` event will be called only once, but images have a *separate* load event.
Pekka
@rryst: The `onload` handler (like all other handlers) applies to the element it is attached to.
You
Also sounds like you have an issue with your images since you want them to reload when the page loads. See my answer on how to have placeholders that will load the actual image
mplungjan
Also, if you ever think of making onload fire only once, you can remove the element's onload property during reloadImage function.
syockit
+1  A: 

You're using this correctly, however that looks like something that might result in your function being called repeatedly if the image loads, however I doubt an image loaded from # is going to ever load. Are you sure that's what you want?

(Why are you calling your code a "document"?)

Matti Virkkunen
A: 

The code SHOULD work, however since you do not have an image in the tag, the onload has nothing to trigger on

Try this

<img src="blank.gif" id="mypic" onload="reloadImage(this);"/>

and test

if (imageElement.src.indexOf('blank')!=-1) imageElement.src="http://www.somedomain.com/image.png";
mplungjan