Communities for your favorite technologies. Explore all Collectives
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Find centralized, trusted content and collaborate around the technologies you use most.
Stack Internal
Knowledge at work
Bring the best of human thought and AI automation together at your work.
How can we call an JavaScript function inside tag attribute ?
let imageURL = () => 'http://www.example.com/image.png';
<img alt="error" src="javascript:imageURL()">
src accepts only url, you can place your function here: <img alt="Not available" src="whatever" onload="this.onload=null; this.src=imageURL();"/>
src
<img alt="Not available" src="whatever" onload="this.onload=null; this.src=imageURL();"/>
Add a comment
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" />
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();" />
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">
Required, but never shown
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.
Explore related questions
See similar questions with these tags.