Advance To A Particular Slick Slide or Center using slickGoTo

In this blog, we will learn how to advance to a particular slide using slick carousel’s slickGoTo method.

Step 1: Get the carousel Element and all the slide items.

const carouselEl = $( '.your-carousel-parent-selector' );
const allSlideItems = $( '.your-carousel-parent-selector .slick-slide');

Step 2: Now get the current Slide.

/**
 * Get Current Slide.
 * @param slideItems
 * @return {*|jQuery|null}
 */
getCurrentSlide( slideItems ) {
   if ( !slideItems.length ) {
      return null;
   }
   
   let slideIndex = null;
   
   for( let i = 0; i < slideItems.length; i++ ) {
      const slideItemEl = $( slideItems[i] );
      if ( slideItemEl.hasClass( 'current-menu-item' ) ) {
         slideIndex = slideItemEl.data('slick-index');
         
         // Make sure it's a non-negative slide
         if ( slideIndex > 0 ) {
            return slideIndex;
         }
      }
   }
   
   return slideIndex;
}

Step 3: Now using the currentSlideIndex move the carousel item position to the current index.

const carouselEl = $( '.your-carousel-parent-selector' );
const allSlideItems = $( '.your-carousel-parent-selector .slick-slide');const currentSlideIndex = this.getCurrentSlide( slideItems );if ( null !== currentSlideIndex ) {
    carouselEl.slick( 'slickGoTo', currentSlideIndex );
}

Please note that this will always keep the position of the current slide as the first element in the carousel. If you want the current slide to remain in the center. Please make sure to set the center mode of the carousel to true by adding that to the setting like so :

carouselEl.slick( {
   dots: false,
   centerMode: true.
}}

That’s all folks!

Leave a Reply