Issue
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?
Solution
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>
Answered By - CoderPi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.