This question has been flagged
5 Replies
2205 Views

I have this code in javascript to change the product image on mouse over. It is working fine, but only for two first products. Last one is being ignored.

```

var list = document.querySelectorAll('span[data-oe-id] img');


for(let i=0; i<list.length; i++){

    let image = list[i];

    let src = image.src;


    image.addEventListener("mouseover",function(event){

     console.log(src);

     image.src="https://media1.giphy.com/media/PfFtibPKBbQrK/giphy.gif?cid=ecf05e47b668e5062e9a561e681f23705e106d8d495b3915&rid=giphy.gif";

    });

    image.addEventListener("mouseout",function(event){

      image.src=src;

    });

}


Here is the video example of issue - https://mega.nz/file/aRUziACJ#bwTlV1wWd_P3kyqYARikyJC-o8hVszJikE_NDaM-jkw


I can't see why it is ignoring the last product, because it has the same HTML code structure as first two products


Resulting HTML code in the shop. My script is - mainimg.js (Yea. I know that js is loaded 3 times, just couldn't find way to load it once): https://pastebin.com/KPFuGnWA



Speaking about my templates code, there's nothing special, just an xpath for card and oe_product_cart classes

Avatar
Discard
Best Answer

I am not sure but I think the issue is in the for loop or list variable and it is not reaching to last product.

Please check if list variable contains all the products and also the for loop is going through all of the products.

Except these 2 points, I don't see any issue in your code.



Avatar
Discard
Author Best Answer

@Sudhir Arya Thank you for your answer, I tried to do list.length + 1 , but it didn't help


Edit: Strange thing about nodes. https://prnt.sc/sf6jn8
In node(1) there's website logo. Node(2) website logo + product 1. Node(3) website logo + product 1 + product 2


Avatar
Discard

Console the list variable and check if it has all the products or not

I think "span[data-oe-id] img" will not simply work. You will have to add something unique for the product images only and us it in the JS as query selector.

Author

Edit#2: I have edited my js code to be more unique to the products, so it will not pick up the website_logo. but issue persists. Third product image remains unchanged on mouseover.

New js code:

var list = document.querySelectorAll('span[data-oe-id].d-flex.h-100 img');

for(let i=0; i<3; i++){

let image = list[i];

let src = image.src;

image.addEventListener("mouseover",function(event){

image.src="https://media1.giphy.com/media/PfFtibPKBbQrK/giphy.gif?cid=ecf05e47b668e5062e9a561e681f23705e106d8d495b3915&rid=giphy.gif";

});

image.addEventListener("mouseout",function(event){

image.src=src;

});

}