Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert Javascript code inside img src

I've tried to insert Javascript code to a src tag from an img, the code looks like:

<img id="p1" width="90%" height="100%" src="javascript:img_info();" />

So basically it gets an image out of an API since the function img_info(); generates a link. The problem is that when i run this code it doesn't return anything, any ideas?

like image 981
bernatixer Avatar asked Oct 22 '25 07:10

bernatixer


2 Answers

Sorry, javascript: is not aviable for the src attribute. And src="img_info()" is not possible as well.


This is how you can do it:

<img id="p1" width="90%" height="100%" src="" />
<script>document.getElementById("p1").src = img_info()</script>

Note that onload won't trigger with an empty src="" attribute! <img onload="this.src = img_info()" /> wont't work.


Live Example:

<script>
  function img_info() {
    return "https://upload.wikimedia.org/wikipedia/commons/c/c2/Faust_bei_der_Arbeit.JPG"
  }
</script>


<img id="p1" width="90%" height="100%" src="" />
<script>
  document.getElementById("p1").src = img_info()
</script>
like image 68
CoderPi Avatar answered Oct 23 '25 20:10

CoderPi


Now, you can put in a errant SRC and use the onload event if you prefer to keep it all within a tag.

<img src="bogus.url" onError="initImage(this)">
like image 20
Joe Love Avatar answered Oct 23 '25 19:10

Joe Love



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!