I want to add multiple event handlers on multiple HTML elements with the same class. I am using a forEach loop to achieve this. But for some reason it doesn’t work as it should.
The first time I had a function to do this. I have multiple of images with the same class so I want to use a forEach loop to able to do an event at once. It’s otherwise really annoying to type the same thing everytime.
This is before:
HTML
<img src="image.png" class="changeImg" onMouseOver="changeToGif(this);" onMouseOut="changeToImg(this);">
<img src="image.png" class="changeImg" onMouseOver="changeToGif(this);" onMouseOut="changeToImg(this);">
<img src="image.png" class="changeImg" onMouseOver="changeToGif(this);" onMouseOut="changeToImg(this);">
<script type="text/javascript" src="script.js"></script>
Javascript
function changeToGif(x){
x.src = "gif.gif";
}
function changeToImg(x){
x.src = "image.png";
}
This is after:
HTML
<img src="image.png" class="changeImg">
<img src="image.png" class="changeImg">
<img src="image.png" class="changeImg">
<script type="text/javascript" src="script.js"></script>
Javascript
let gifs = document.querySelectorAll(".changeImg");
gifs.forEach(gif => {
gif.addEventListener("mouseover", () => {
this.src = "gif.gif";
});
gif.addEventListener("mouseout", () => {
this.src = "image.png";
});
});
SNIPPET:
let gifs = document.querySelectorAll(".changeImg");
gifs.forEach(gif => {
gif.addEventListener("mouseover", () => {
this.src = "https://gifimage.net/wp-content/uploads/2017/08/tree-gif.gif";
});
gif.addEventListener("mouseout", () => {
this.src = "https://cdn.pixabay.com/photo/2018/05/31/10/03/big-tree-3443533_640.jpg";
});
});
<img src="https://cdn.pixabay.com/photo/2018/05/31/10/03/big-tree-3443533_640.jpg" class="changeImg">
<img src="https://cdn.pixabay.com/photo/2018/05/31/10/03/big-tree-3443533_640.jpg" class="changeImg">
<img src="https://cdn.pixabay.com/photo/2018/05/31/10/03/big-tree-3443533_640.jpg" class="changeImg">
<script type="text/javascript" src="script.js"></script>
Why is this not working? It seems like I’m still missing something in the code. But I don’t know what exactly what.
>Solution :
The problem were :
- moveover instead of mouseover
- this instead of gif in forech loop
let gifs = document.querySelectorAll(".changeImg");
gifs.forEach(gif => {
gif.addEventListener("mouseover", () => {
gif.src = "https://gifimage.net/wp-content/uploads/2017/08/tree-gif.gif";
});
gif.addEventListener("mouseout", () => {
gif.src = "https://cdn.pixabay.com/photo/2018/05/31/10/03/big-tree-3443533_640.jpg";
});
});
.changeImg {
width:100px;
height:100px
}
<img src="https://cdn.pixabay.com/photo/2018/05/31/10/03/big-tree-3443533_640.jpg" class="changeImg">
<img src="https://cdn.pixabay.com/photo/2018/05/31/10/03/big-tree-3443533_640.jpg" class="changeImg">
<img src="https://cdn.pixabay.com/photo/2018/05/31/10/03/big-tree-3443533_640.jpg" class="changeImg">