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?
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>
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)">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With