Disable scrolling to the gallery on variant change in Shopify Dawn theme
Dawn theme in Shopify by default changes the order of images depending on the variant selection and automatically scrolls to the gallery container.
This all works great but on mobile it scrolls the user to the top and the user has to scroll back down if he wants to select another variant or add to cart.
For the Dawn theme this code is present in the /assets/media-gallery.js file. We want to keep the image order swap when switching variants but disable the scrolling to the gallery. The following code does that.
// In the setActiveMedia method on line 31 find
// the window.setTimeout function and chage it to the following.
window.setTimeout(() => {
if (this.elements.thumbnails) {
activeMedia.parentElement.scrollTo({ left: activeMedia.offsetLeft });
}
if (!this.elements.thumbnails || this.dataset.desktopLayout === 'stacked') {
// Disable scrolling to gallery on variant change
// activeMedia.scrollIntoView({ behavior: 'smooth' });
// Still change the slide to the selected variant
activeMedia.parentElement.scrollTo({ left: activeMedia.offsetLeft });
}
});
The above code is working for the Dawn theme version < 13. If you have the newer theme version the code is a little bit different. It is still inside the /assets/media-gallery.js file. Around line 48 comment out the code so it looks like bellow, this will disable the scrolling to the image.
window.setTimeout(() => {
if (!this.mql.matches || this.elements.thumbnails) {
activeMedia.parentElement.scrollTo({ left: activeMedia.offsetLeft });
}
// Comment out the bellow lines to disable scrolling
// const activeMediaRect = activeMedia.getBoundingClientRect();
// Don't scroll if the image is already in view
// if (activeMediaRect.top > -0.5) return;
// const top = activeMediaRect.top + window.scrollY;
// window.scrollTo({ top: top, behavior: 'smooth' });
});