views:

31

answers:

1

I'm wondering how you can substitute the src-property (or delete the whole img-node) with JavaScript, if the browser is realizing, that the image beyond the image-src-property doesn't exist (any more).

For example:

<div id="foo">
   <img src="bar">
</div>

And the img-tag is pointing to nowhere. In some browser, esp. the iE, are showing a "no image" cross. I prefer to substitute bar with an alternative image url or substitute the img-node with a nbsp.

I found an approach, that doesn't really worked for me.

Please suggest me solutions only with PrototypeJS or raw JS (its a project which is using PrototypeJS and I don't wanna overload it with other frameworks).

best wishes

chris

+1  A: 

Just use an onerror handler for the image, and inside the handler, either delete the node or change the src:

<img src="..." id="img-1"
     onerror="document.getElementById('img-1').src='working image';">

Or alternately:

<img src="..." id="img-1"
     onerror="document.getElementById('img-1').parentNode.removeChild(document.getElementById('img-1'));">

It's probably better to write that as an event handler and attach it to all images in the document.

bluesmoon
I've tried the first solution and it works fine.But what about the IDs if you have dynamic-many img's in your document? Can't you use _this_ or something else?
ChrisBenyamin
If you write an event handler, and attach that to the image, then you can use `this`. In an inline script, `this` will refer to the `window` object.
bluesmoon
The onerror property is not strict xhtml, so I had to vote down for this answer.
ChrisBenyamin
seriously? perhaps the title of this question should mention strict XHTML
bluesmoon