4

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?

1
  • This post provides reasonable solutions. Commented Dec 25, 2015 at 23:03

3 Answers 3

16

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>

Sign up to request clarification or add additional context in comments.

Comments

2

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)">

Comments

-1

Put it in an onload event instead and set the src with setAttribute.

So something like

<img onload="this.setAttribute('src', img_info())" >

1 Comment

As it was pointed in the chosen answer, this won't work, because onload event will not trigger before a src has being defined.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.