1

How can we call an JavaScript function inside tag attribute ?

let imageURL = () => 'http://www.example.com/image.png';
<img alt="error" src="javascript:imageURL()">

4 Answers 4

3

src accepts only url, you can place your function here: <img alt="Not available" src="whatever" onload="this.onload=null; this.src=imageURL();"/>

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

Comments

1

Use JavaScript to change the image src attribute:

document.getElementById('myImage').src = 'https://media.wired.com/photos/5b8999943667562d3024c321/master/w_2560%2Cc_limit/trash2-01.jpg';
<img alt="Not available" id="myImage" />

Comments

1

you can not run js function on attribute, try this function first it try to load placeholder, after placeholder loaded it then trigger JS function

<img src="https://thumbs.gfycat.com/RapidRadiantBug-small.gif" onload="this.onload=null; this.src=imageURL();" />

Comments

0

Use javascript to change image source, see my example :

document.getElementById('image').setAttribute('src', 'https://media.wired.com/photos/5b8999943667562d3024c321/master/w_2560%2Cc_limit/trash2-01.jpg');
<img alt="Not available" src="" id="image">

Comments

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.