I'm very new to JavaScript (I have very limited Python experience as well) and am trying to find a simple way to call an object property from another .js file I have feeding into my HTML base file.
Snip of flowers.js
const rose = {name:'Rose', color:'Red', pic:'Rose.png'};
Snip of HTML base file
<html>
<head>
<script src="flowers.js"></script>
</head>
<body>
<img id='flowerOne' src=rose.pic style='width:100px'>
</body>
</html>
This works fine if I paste the image reference in directly ("Rose.png" within img src) but not if I write out rose.pic, which theoretically has the exact same reference? I've managed to get .js file functions to work just fine, it just seems to be calling object properties where I'm struggling.
I'm probably not understanding something - any help is appreciated. Thank you!
CodePudding user response:
You can change the source of the image in javascript. Just use this
flowers.js
const rose = {name:'Rose', color:'Red', pic:'Rose.png'};
document.getElementById('flowerOne').src = rose.pic
HTML:
<html>
<head>
</head>
<body>
<img id="flowerOne" style='width:100px'>
<script src="flowers.js"></script>
</body>
</html>
CodePudding user response:
One approach is to use JavaScript to update the src
attribute of the html img. You can accomplish that by first selecting the image as follows:
let img = document.querySelector('img');
Then you can assign it a new src
attribute value as follows:
img.src = rose.pic;
The image can have an empty src
attribute, a placeholder image, or no src
attribute at all. Your choice.