The previous answer provides a good solution, but an alternative method might offer more flexibility. Instead of embedding a function call directly in the HTML, you can assign a custom data attribute to your image element with a value that represents your function name. After the page loads, JavaScript can target images using this attribute, retrieve the function name, invoke the function from the global scope, and then update the src attribute with the returned value.
This approach helps keep your HTML clean and separates your markup from your logic, which is particularly useful if you need to handle multiple images.
I’ve actually tackled a similar issue in one of my projects. Instead of trying to use JavaScript directly in the HTML src attribute, which won’t work as you’ve discovered, I’d recommend using JavaScript to set the src after the page loads.
Here’s what worked for me:
Give your img tag an id:
Then use JavaScript to set the src:
document.addEventListener(‘DOMContentLoaded’, function() {
document.getElementById(‘companyLogo’).src = getLogoPath();
});
This approach lets you keep your getLogoPath() function and dynamically set the image source once the DOM is ready. It’s clean, efficient, and avoids mixing JavaScript directly into your HTML attributes.