The for loop is not working to expand the image.
When I place an index at the end, it works. So I know indirectly that there is nothing wrong with HTML and CSS, and that the function works.
const expandImage = document.getElementsByClassName('website_image')[0];
expandImage.addEventListener('mouseover', expand);
function expand(event){
expandImage.style.padding='11%';
}
However, when I attempt to do a for loop:
const expandImage = document.getElementsByClassName('website_image');
for(let i=0; i<expandImage.length; i++) {
expandImage.addEventListener('mouseover', expand);
function expand(event){
expandImage.style.padding='11%';
}
}
Nothing happens.
What am I doing wrong?
You're not referencing the array element in your loop, you're referencing the whole array. You need to use the equivalent of
[0]
inside your loop, in this case,[i]
.But you'll find this won't work either! You can't access
expandImage[i]
within your function because by the time it executes,i
is equal toexpandImage.length
. You'll need to store a reference in the declaring scope for the current element ofexpandImage
, or it might be simpler to just use thethis
object in your method: