I wrote a custom Shopify section. The section contains a slider, and each block added to the section results in a new slide added to the slider.
When editing slides (blocks), the slider should automatically slide to the selected block for proper preview experience. I wrote a js function for that, that works perfectly fine:
if (Shopify.designMode) {
document.addEventListener('shopify:block:select', function(event) {
const sectionSelectedIsHero = event.target.classList.contains('hero-slide');
if(!sectionSelectedIsHero) return;
var selectedSlideId = $(event.target).attr("data-slide-id");
heroCarousel.to(selectedSlideId);
});
}
However, when a user edits a slide (block), for example the background color in a color picker, Shopify automatically reloads the section in the ThemeEditor to update the preview for the user.
While the shopify:block:select event is being fired again (I can track "event" variable in console.log()), the slider doesnt work at all after that. The first slide is in preview and the controls also stop working. When selecting different slides (blocks), nothing happens.
Appreciate any help. Thanks!
EDIT: I now have a working solution. However, this is not optimal at all as im repeating code just to make it execute again. How can I avoid that? Does anyone have a suggestion?
$( document ).ready(function() {
var heroCarouselElement = document.querySelector('#heroCarousel');
var heroCarousel = new bootstrap.Carousel(heroCarouselElement, {
interval: false,
keyboard: false,
wrap: true,
touch: true
});
$("#heroControlPrev").click(function() { heroCarousel.prev(); });
$("#heroControlNext").click(function() { heroCarousel.next(); });
if (Shopify.designMode) {
document.addEventListener('shopify:block:select', function(event) {
const sectionSelectedIsHero = event.target.classList.contains('hero-slide');
if(!sectionSelectedIsHero) return;
var selectedSlideId = $(event.target).attr("data-slide-id");
var heroCarouselElement = document.querySelector('#heroCarousel');
var heroCarousel = new bootstrap.Carousel(heroCarouselElement, {
interval: false,
keyboard: false,
wrap: true,
touch: true
});
$("#heroControlPrev").click(function() { heroCarousel.prev(); });
$("#heroControlNext").click(function() { heroCarousel.next(); });
heroCarousel.to(selectedSlideId);
});
}
});
On my mind, the issue is about the event.
You might try this:
if (Shopify.designMode) {
document.addEventListener('shopify:section:load', function(event) {
/* Do something */
});
}
As explained in doc the load event is fired when "A section has been added or re-rendered." Which is the case each time user add a slide (re-rendering).
Please not that you might have to reset/clear the function initializing the slider before, using the unload event (depending the way the slider works).