Reputation: 83
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?
Upvotes: 4
Views: 27403
Reputation: 5982
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)">
Upvotes: 2
Reputation: 1
Put it in an onload
event instead and set the src
with setAttribute
.
So something like
<img onload="this.setAttribute('src', img_info())" >
Upvotes: -1
Reputation: 13221
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>
Upvotes: 16