Jump to content

image replace with JS - help :)


Recommended Posts

Hi all!

I wonder if you could help me. I'm trying to add a bit of JS code so that on product page, the product image is replaced with smaller size on mobile devices. I got it working on all product images except for the active image (cover) and the next one. From what I'm guessing, I think jquery is overriding my code, but I can't figure out a way to stop that from happening. If I add my code in the browser console it works perfectly with all images, but when I include the code in custom.js or theme.js (or via theme configuration - it has a custom js section) it doesn't work.

I'm using Warehouse 4.4.2 template on Prestashop 1.7.

My code is:

 

const metaTagValue = document.querySelector('meta[property="og:type"');
const imageToReplace = document.querySelectorAll('#product-images-large .product-lmage-large img');
const thumbClick = document.querySelectorAll('img.thumb.js-thumb.img-fluid.swiper-lazy.swiper-lazy-loaded');
if (metaTagValue.content === 'product') {
    function replaceImages() {
        if (imageToReplace.length !== 0 && window.innerWidth <= 767) {
            for (const replacedImg of imageToReplace) {
                let x = `${replacedImg.dataset.src}`;
                let y = `${replacedImg.src}`;
                if (x.includes('large_default')) {
                    replacedImg.src = `${x.replace('large_default', 'home_default')}`;
                    replacedImg.width = '360';
                    replacedImg.height = '360';
                } else if (y.includes('large_default')) {
                    replacedImg.src = `${y.replace('large_default', 'home_default')}`;
                    replacedImg.width = '360';
                    replacedImg.height = '360';
                }
            }
        }
    }

    replaceImages();
    for (eachThumb of thumbClick) {
        eachThumb.addEventListener('click', () => {
            replaceImages();
        })
    }

}

The website is www.cbdstore.ie but I'm trying it on test environment with template v 4.4.2, while the production site is 4.4.1.

Any tips would be much appreciated!

Edited by matik4 (see edit history)
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...