Search code examples
javascriptvue.jsvuejs3nuxt.jsnuxt3.js

Instantly set Embla Carousel slide index without animation


I’m building a gallery component in where clicking on an image opens a <dialog> containing an embla-carousel. The problem is that when I click on an image, the carousel always opens at index 1, regardless of which image was clicked. I tried to fix this by using emblaMainApi.scrollTo(selectedIdx.value) to get to the carousel's position based on the clicked image index, but this causes an scrolling animation from slide 1 to the selected slide, which looks weird.

I want the selected image to appear instantly in the carousel without any scrolling animation.

I'm looking for a possible solution.

// gallery.vue template
<template>
<div>
  <ItemModal ref="modalRef" :imgs="imgs" />
  <div v-for="(item, idx) in imgs" :key="item">
    <NuxtImg
    :src="`${item}`"
     :alt="`gallery image ${idx}`"
    @click="showImg(idx)"
    />
  </div>
</div>
</template>

// gallery.vue script
const imgs = [
  "/images/gallery/gallery-1.jpg",
  "/images/gallery/gallery-2.jpg",
  "/images/gallery/gallery-3.jpg",
];

const modalRef = ref(null);

const showImg = (index) => {
  if (modalRef.value) {
    modalRef.value.show(index);
  }
};

// modal.vue script. Here I expose the 'show' method to the 'gallery' parent component so I can use it there
defineExpose({
  show: (index: number) => {
    selectedIdx.value = index;
    isOpen.value = true;
    dialog.value?.showModal(); // showModal() is a native `dialog`'s method
  },
});

Solution

  • The issue is solved by setting a jump parameter to true in the scrollTo method.