My class assignment wants me to use the defer
tag for the script I am referencing, but this leads to the image's naturalWidth
being undefined due to the order of execution in my js file.
My HTML has this line in the head (assignment wants me to put it in the <head>
but use defer="defer"
)
<script src="scripts/script.js" defer="defer"></script>
My js:
var catImageWidth = document.getElementById("cat-image").naturalWidth;
var birdImage = document.getElementById("bird-image");
birdImage.width = catImageWidth;
So I tried this:
var catImage = document.getElementById("cat-image");
var birdImage = document.getElementById("bird-image");
var catImageWidth;
catImage.onload = function() {
catImageWidth = this.naturalWidth;
console.log(catImageWidth) //logs 600
}
birdImage.width = catImageWidth; //logs `undefined`
I think that the assignment of birdImage.width
is undefined because this line of code runs before catImage.onload
actually happens. Does this mean that I'm slave to assigning birdImage.width
within the scope of the function
of catImage.onload
?
P.S. I tried ES6 of catImage.onload = () => { //block of code }
but this didn't seem to work.
The issue is that you are trying to access a variable out of scope.
Please give this a try:
<img id="cat-image" src="https://static.pexels.com/photos/104827/cat-pet-animal-domestic-104827.jpeg">
<img id="bird-image" src="http://animalia-life.club/data_images/bird/bird3.jpg">
<script>
var catImage = document.getElementById("cat-image");
var birdImage = document.getElementById("bird-image");
var catImageWidth;
catImage.onload = function() {
catImageWidth = this.naturalWidth;
birdImage.width = catImageWidth;
}
console.log(birdImage.width);
</script>