The colors of the active Svelte Carousel navigation dots do not smoothly transition along with the slides

Currently, I am developing a carousel feature using schadcn-svelte and embla carousel. Everything seems to work fine initially - when clicking on dot 2, it transitions smoothly from slide 1 to slide 2, and the active dot styles update correctly. However, after this initial interaction, the active state of the navigation dots stops updating, and there is a noticeable lag in slide transitions. I am quite puzzled by this issue as it appears to function properly at first but then becomes glitchy. Any assistance to resolve this matter would be greatly valued. Here is the snippet of my current code:

<script lang="ts">
  import * as Card from "$lib/components/ui/card/index.js";
  import type { CarouselAPI } from "$lib/components/ui/carousel/context";
  import * as Carousel from "$lib/components/ui/carousel/index.js";
  import { projects } from "../data/slides";
  import { MoveRight } from "lucide-svelte";
  import emblaCarouselSvelte from "embla-carousel-svelte";

  // CAROUSEL

  let slideAxisOffset = -1000;
  let duration = 500;

  let carouselApi: CarouselAPI;
  let carouselWrapperWidth: number;

  let activeCarouselItemId = 0;
  function setActiveCarouselItem(index: number) {
    carouselApi.scrollTo(index);
    activeCarouselItemId = index;
  }

  let apiSet = false;

  let interval = setInterval((): any => {
    if (carouselApi) {
      carouselApi.on("scroll", (carouselApi) => {
        activeCarouselItemId = carouselApi.slidesInView()[1];
      });
      apiSet = true;
      clearInterval(interval);
    }
  });

  let carouselRootEl: HTMLElement;
</script>

<Carousel.Root
  opts={{
    // align: "center",
    loop: true,
  }}
  class="w-full bg-black"
  bind:api={carouselApi}
>
  <Carousel.Content class="">
    {#each projects as project}
      <Carousel.Item class="basis-1/2 hover:cursor-grab border-none">
        <div class="my-4 border-none">
          <Card.Root class="border-none">
            <Card.Content
              class="flex h-[60vh] p-6 rounded-lg border-none"
              style="background-image: url({project.image}); background-repeat: no-repeat; background-size: cover;"
            >
              <div class="absolute top-12 left-12 h-full text-white uppercase">
                <h2 class="text-2xl font-semibold">{project.title}</h2>
                <p class="text-xl font-normal">{project.description}</p>
                <button
                  class="flex items-center gap-2 absolute bottom-24 left-0 uppercase font-black text-xl tracking-wider border-2 rounded-full py-2 px-6 hover:bg-white/50 ease-in-out duration-300"
                  >Explore <MoveRight size="40" /></button
                >
              </div></Card.Content
            >
          </Card.Root>
        </div>
      </Carousel.Item>
    {/each}
  </Carousel.Content>
</Carousel.Root>
<!-- Progress circles -->
<div class="flex space-x-2 bg-black w-full items-center justify-center py-12">
  {#each projects as item, idx}
    <button
      on:click={() => {
        setActiveCarouselItem(idx);
      }}
      class="rounded-full aspect-square w-4 {idx === activeCarouselItemId
        ? 'bg-white'
        : 'bg-white/30'}"
    ></button>
  {/each}
</div>

I am still new to Svelte and TypeScript, so any suggestions or guidance would be highly appreciated!

Answer №1

Example of Implementation

<script lang="ts">
  import * as Card from "$lib/components/ui/card/index";
  import * as Carousel from "$lib/components/ui/carousel/index";
  import type { CarouselAPI } from "$lib/components/ui/carousel/context";

  let carouselApi: CarouselAPI;
  let activeCarouselItemId = 0;
  function setCurrentCarouselItem(index: number) {
    carouselApi.scrollTo(index);
    activeCarouselItemId = index;
  }
  $: {
    if (carouselApi) {
      carouselApi.on("select", (e) => {
        activeCarouselItemId = carouselApi.selectedScrollSnap();
      });
    }
  }
</script>

<div>
  <Carousel.Root
    opts={{
      loop: true,
    }}
    class="w-full max-w-xs"
    bind:api={carouselApi}
  >
    <Carousel.Content>
      {#each Array(5) as _, i (i)}
        <Carousel.Item>
          <div class="p-1">
            <Card.Root>
              <Card.Content
                class="flex aspect-square items-center justify-center p-6"
              >
                <span class="text-4xl font-semibold">{i + 1}</span>
              </Card.Content>
            </Card.Root>
          </div>
        </Carousel.Item>
      {/each}
    </Carousel.Content>
    <Carousel.Previous />
    <Carousel.Next />
    <div
      class="flex space-x-2 bg-black w-full items-center justify-center py-12"
    >
      {#each { length: 5 } as item, idx}
        <button
          on:click={() => {
            setCurrentCarouselItem(idx);
          }}
          class="rounded-full aspect-square w-4 {idx === activeCarouselItemId
            ? 'bg-white'
            : 'bg-white/30'}"
        ></button>
      {/each}
    </div>
  </Carousel.Root>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can Node / Javascript import various modules depending on the intended platform?

Is there a way to specify which modules my app should import based on the target platform in TypeScript? I am interested in importing different implementations of the same interface for a browser and for Node.js. In C++, we have something like: #ifdef wi ...

Limit the elements in an array within a specified range of dates

Currently, I am working on implementing a filter functionality for a data array used in a LineChart within my Angular application using TypeScript. The structure of the data array is as follows: var multi = [ { "name": "test1", "series": [ ...

The situation I find myself in frequently is that the Angular component Input

There seems to be an issue with a specific part of my application where the inputs are not binding correctly. The component in question is: @Component({ selector : 'default-actions', templateUrl : './default.actions.template.html&a ...

Ways to modify a mongoose find query to return null instead of throwing a CastError in case of incompatible types

Issue When utilizing mongoose to search for docs by a particular field, if the data type of the field differs from the data type of the queried value, mongoose will try to convert the query value to match the field's data type. However, if the conve ...

What is the best approach to deactivate or manage init and toJSON functionalities?

After creating a .NET core 2.2 webapi and utilizing swagger / nswag to generate the API for my React / typescript application, I encountered a ts(2739) message when attempting to set up a new object: Type '{ firstName: string; lastName: string; }&ap ...

What is the best way to showcase pictures retrieved from Cordova PhotoLibrary?

I've encountered an issue with displaying images in the Image Gallery on my Android device. Although the PhotoLibrary plugin successfully returns a list of image URLs, I am having difficulty loading them into img tags. window['cordov ...

Adjusting the return type based on the relationships defined in a Prisma object

Is there a way to implement a function that takes a Prisma object and dynamically sets the return type based on the included relations? I am aiming to type versionWithRelations with properties like pages, variables, and actions, while versionWithoutRelati ...

Struggling to chart out the post response in Angular 7

I am facing an issue while setting up a service on Angular version 7. The problem arises with the res.json() method, throwing an error stating Property 'json' does not exist on type 'Object'. Below is my service's code: import {In ...

Executing TypeScript functions that call multiple times to change the innerHTML of an Angular div

My array consists of objects with dates spanning approximately 2 years, prices (which are added dynamically post API calls), and changeable validations within the Angular app: calendarArrayDates = [ {"date": "2018-10-23", "price":"2313", "date_is_valid" ...

Lock the table header in place as the table content scrolls upward using Angular4

Is there a way to keep the table header fixed in place while the rest of the content scrolls up? Below is a snippet from my .html file: <table class="table sticky-header"> <thead> <tr class="row-hor- ...

Utilizing i18next for both a custom Typescript library and a host simultaneously: a step-by-step guide

Currently, I am in the process of developing a typescript library that is designed to take in an object and generate an excel file. This library is intended for use with multiple React applications. Each React application, or host, will provide its own obj ...

What steps can I take to eliminate the overload error that occurs when I extend the Request object in Express?

I'm having trouble extending Express' Request object to access req.user, and I'm encountering an overload error. I've attempted a couple of solutions, but none of them seem to work for me. EDIT: I am currently using Passport.js and JWT ...

Typescript is encountering issues with generating incorrect triple slash directives

After updating to typescript 3.7.3, I noticed that my main index.d.ts file contains invalid triple slash directives after building the project. Below is a snippet of my index.d.ts : /// <reference path="types/augmentations.d.ts" /> /// <referenc ...

Selecting a filter for an array of objects

I'm struggling to implement a search feature in my mat-select DropDown. The existing options I've found online aren't quite working for me due to the object array I am passing to the Dropdown. Any assistance or guidance on this matter would ...

Encountering an issue with PrimeNG's <p-calendar> component: the error message "date

I encountered an issue resulting in the following error message: core.es5.js:1020 ERROR Error: Uncaught (in promise): TypeError: date.getMonth is not a function TypeError: date.getMonth is not a function This error occurs whenever I attempt to implement ...

Modifying the values of various data types within a function

Is there a more refined approach to enhancing updateWidget() in order to address the warning in the else scenario? type Widget = { name: string; quantity: number; properties: Record<string,any> } const widget: Widget = { name: " ...

Version 1.9.3 of Redux Toolkit is encountering an error stating that the 'push' property is not found on the type 'WritableDraft<CartState>'

Currently delving into Redux Toolkit using TypeScript and facing a roadblock that seems deceptively simple. Unfortunately, my current knowledge isn't enough to unravel this puzzle and I'm in need of some guidance. The issue arises with an error ...

Easiest Angular Carousel Solution

My goal is to create a basic Angular Carousel to enhance my understanding of Angular. While I have received helpful answers in the past, I am seeking further clarification to deepen my knowledge of Angular2+ and Typescript. Here's what I have so far: ...

Tips for correctly displaying diacritics with Webpack and Typescript

While working on my project, I encountered an issue with diacritics marks (such as German or Polish characters) when using Webpack with Typescript. Unfortunately, the problem arises when trying to display these marks in the console or on a webpage. It seem ...

The Nextjs next-auth implementation with URL '/api/auth/callback/cognito' encountered a 502 Bad Gateway error while in production

I'm facing a challenge while trying to deploy a nextjs app that utilizes 'next-auth' with AWS Cognito. Interestingly, the app runs smoothly when tested locally using either next dev or next start. However, upon deploying it on the producti ...