Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IMG SRC tags and JavaScript

Is it possible to call a JavaScript function from the IMG SRC tag to get an image url?

Like this:

<IMG SRC="GetImage()" />

<script language="javascript">
   function GetImage() {return "imageName/imagePath.jpg"}
</script>

This is using .NET 2.0.

like image 537
David Avatar asked Sep 22 '08 19:09

David


3 Answers

Nope. It's not possible, at least not in all browsers. You can do something like this instead:

<img src="blank.png" id="image" alt="just nothing">
<script type="text/javascript">
    document.getElementById('image').src = "yourpicture.png";
</script>

Your favourite JavaScript framework will provide nicer ways :)

like image 106
Armin Ronacher Avatar answered Nov 20 '22 22:11

Armin Ronacher


If you're in the mood for hacks, this works as well.

<img src='blah' onerror="this.src='url to image'">
like image 22
jdizzle Avatar answered Nov 20 '22 21:11

jdizzle


Is it possible to call a JavaScript function from the IMG SRC tag to get an image url?

Do you mean doing something like the following?

<img src="javascript:GetImage()" />

Unfortunately, no - you can't do that. However, you can do the following hack:

function getImageUrl(img) {
   var imageSrc = "imageName/imagePath.jpg";
   if(img.src != imageSrc) { // don't get stuck in an endless loop
      img.src = imageSrc;
   }
}

Then, have the following html:

<img src="http://yourdomain.com/images/empty.gif" onload="getImageUrl(this)" />

The onload event will only fire if you have an actual image set to the src attribute - if you don't set that attribute or set it to an empty string or something similar, you will get no love. Set it to a single pixel transparent gif or something similar.

Anyway, this hack works, but depending on what you are really trying to accomplish, this may not be the best solution. I don't know why you would want to do this, but maybe you have a good reason (that you would like to share with us!).

like image 9
Jason Bunting Avatar answered Nov 20 '22 22:11

Jason Bunting