Javascript not working unless page refresh

Hello, there.

Right now we have a script in which you can select a product variant and according to that, it will only show that variant’s images (not just one). So the js code implemented is this, but it only works if the page is refreshed.

filterImgVariant(){
    if(this.currentVariant.featured_image && this.currentVariant.featured_image.alt){
      //show only the thumbnails for the selected variant
      //[thumbnail-alt = 'rojo']
      document.querySelectorAll('[thumbnail-alt]').forEach(img => img.style.display = 'none')
      const currentImgAlt = this.currentVariant.featured_image.alt
      const thumbnailSelector = [thumbnail-alt = '${currentImgAlt}']
      document.querySelectorAll(thumbnailSelector).forEach(img => img.style.display = 'block')
    }
    else {
      //show all thumbnails
      document.querySelectorAll('[thumbnail-alt]').forEach(img => img.style.display = 'block')
    }
  }

Anyone know what could be added or modified on the code so that it will refresh once the variant is clicked without need to refresh the page?

I learned how to do this from here:

https://www.youtube.com/watch?v=L83SG32LWHc

Hello @marthedesigner ,

You code still has problem at line

const thumbnailSelector = [thumbnail-alt = '${currentImgAlt}']

Please replace it with

const thumbnailSelector = `[thumbnail-alt = '${currentImgAlt}']`

Ooh thanks a lot. I tried this but it freezed all the animations the website had, like tickers and videos. Also the variant change stopped working. Thank you for your time anyways :disappointed_face:

Sure, thanks! https://tiendacharros.myshopify.com/products/babero-azul-rey-ch?_pos=1&_sid=70b85a916&_ss=r

here’s the product with variant.

1 Like