I need to allow the web user to enter a URL for an image, and I want the user to have visual confirmation that the URL is valid (or not).
I would like it so that if the user enters:
- nothing, it will display the default (not found) image.
http://example.com/ValidImageUrl.any_or_no_extension, it will accept it and display the image.hxxp://example.com/ValidImageUrl.any_or_no_extension, it will display the default (not found) imagehttp://example.com/INVALID_imageurl.any_or_no_extension, it will display the default (not found) image. Essentially, if the link is anything but a 200, it should display the defaulthttp://example.com/asdf?qwerty&t=10982741238947, (assuming it is valid) it will automagically determine whether it is a valid image and display it if valid, otherwise display the default (not found) image. This is the hardest case to capture, but is becoming increasingly important in today’s flickr & picassa embedded world… But if the browser can detect it as an image and display it, then javascript should be able to detect it, and identify its particulars.
The following is an extremely simplified example:
<input id="GivenUrl" onblur="UpdateImage()"/>
<img id="UserImage"/>
<script type="text/javascript">
var TextBox = document.getElementById("GivenUrl");
var Image = document.getElementById("UserImage");
if (Image.value == "")
{
UserImage.setAttribute("src", "MyDefaultImage.jpg");
}else{
UserImage.setAttribute("src", encodeURI(TextBox.value));
}
</script>
And finally my constraints: I’d optimally like the solution to be pure HTML / javascript, all processed on the client (user) side. Slightly less favorable solutions would involve .Net server-side processing, which is possible but definitely not optimal…
Any ideas?
Please overlook any benign coding errors in the above, since I am not currently at a machine where I can test my own code…
You are in luck 🙂
Images have an onerror handler, so you don’t have to check the image’s validity (ie, the url might try to return HTML instead of image), you can still cover your back.
Though I’m pretty sure the handler might not be W3C-approved.