I have a few div's with class ".web-item" containing images. I go through them with a for loop and put an addEventListener (mouseover) on all the iterations and try to change the styling of each element (always the hovered element's style). But as I hover over an element, the styling of all the elements changes following the hovered element.
This is my JavaScript code:
let webItems = document.querySelectorAll(".web-item");
let i = 0;
for (let i = 0; i < webItems.length; i++) {
webItems[i].addEventListener("mouseover", function() {
webItems[i].style.filter = "brightness(30%)";
webItems[i].children[1].style.display = "block";
});
};
And the HTML:
<div class="web-item web-item-a">
<a href="#" target="_blank">
<img src="img/img-1.jpg" loading="lazy" alt="img-1.jpg">
</a>
<div class="web-item-caption">
<?php echo $lang["web-caption-a"] ?>
</div>
</div>
<div class="web-item web-item-b">
<a href="#" target="_blank">
<img src="img/img-2.jpg" loading="lazy" alt="img-2.jpg">
</a>
<div class="web-item-caption">
<?php echo $lang["web-caption-b"] ?>
</div>
</div>
How could I achieve that only the actually hovered element's styling changes? I would be really grateful for your help.
Only the styling of the hovered element will change - but if you hover over another element afterwards (like if you're moving the mouse quickly), that element's style will change too. You don't have any "stop hovering" functionality at the moment - if the mouse hovers over something, that element's style will stay changed until the page is reloaded.
let webItems = document.querySelectorAll(".web-item");
let i = 0;
for (let i = 0; i < webItems.length; i++) {
webItems[i].addEventListener("mouseover", function() {
webItems[i].style.filter = "brightness(30%)";
webItems[i].children[1].style.display = "block";
});
};
<div class="web-item web-item-a">
<a href="#" target="_blank">
<img src="img/img-1.jpg" loading="lazy" alt="img-1.jpg">
</a>
<div class="web-item-caption">
<?php echo $lang["web-caption-a"] ?>
</div>
</div>
<div class="web-item web-item-b">
<a href="#" target="_blank">
<img src="img/img-2.jpg" loading="lazy" alt="img-2.jpg">
</a>
<div class="web-item-caption">
<?php echo $lang["web-caption-b"] ?>
</div>
While you could add a mouseout listener, this can be achieved with only CSS and :hover:
.web-item-caption {
display: none;
}
.web-item:hover {
filter: brightness(30%)
}
.web-item:hover > .web-item-caption {
display: block;
}
<div class="web-item web-item-a">
<a href="#" target="_blank">
<img src="img/img-1.jpg" loading="lazy" alt="img-1.jpg">
</a>
<div class="web-item-caption">
text 1
</div>
</div>
<div class="web-item web-item-b">
<a href="#" target="_blank">
<img src="img/img-2.jpg" loading="lazy" alt="img-2.jpg">
</a>
<div class="web-item-caption">
text 2
</div>