#Carousel with AlpineJS and Astro

1 messages · Page 1 of 1 (latest)

rustic pike
#

I am trying to follow this tutorial https://carouth.com/articles/flexible-carousel-with-alpinejs/ and copying the code line by line but still it is not working in my website. Here's my code -

<script>
  declare const window: any;
  window.carousel = function () {
  return {
    ...,
    scrollTo(element) {
      const current = this.container;

      if (!current || !element) return;

      const nextScrollPosition =
        element.offsetLeft +
        element.getBoundingClientRect().width / 2 -
        current.getBoundingClientRect().width / 2;

      current.scroll({
        left: nextScrollPosition,
        behavior: 'smooth',
      });
    }
  };
}
</script>

My website is completely not working and it is showing an error, the HTML and CSS is copied exactly the same

Jeff Carouth

I ran across a nice implementation of a carousel primarily with CSS and augmented forward/backward buttons with JavaScript. I wanted to see if I could replicate it using TailwindCSS and AlpineJS. Turns out, I can. Here's how.

quartz roost
#

Have you tried to remove the ..., Part?

rustic pike
quartz roost
#

Do you have a x-data argument in your html if you are using alpine

tight bloom
rustic pike
rustic pike
#

well that still doesnt fix my issue

#

I really want this to work but its not working

tight bloom
rustic pike
tight bloom
rustic pike
tight bloom
#

On the browser console?

rustic pike
tight bloom
#

Hmmm

rustic pike
#

4 error and 3 warning

tight bloom
#

Could you paste that in?

rustic pike
#

Alpine Expression Error: init is not defined

Expression: "init()"

<div class=​"relative overflow-hidden group astro-WRUWT3M6" x-data=​"carousel()​" x-init=​"init()​">​…​</div>​
handleError @ module.esm.js:416
module.esm.js:416 Alpine Expression Error: prev is not defined

Expression: "prev !== null"

<div class=​"hidden md:​block absolute top-1/​2 left-0 bg-white rounded-md transition-transform ease-in-out transform -translate-x-full -translate-y-1/​2 group-hover:​translate-x-0 cursor-pointer astro-WRUWT3M6" x-on:click=​"scrollTo(prev)​" x-show=​"prev !== null" style=​"display:​ none;​">​…​</div>​
handleError @ module.esm.js:416
module.esm.js:416 Alpine Expression Error: next is not defined

Expression: "next !== null"

<div class=​"hidden md:​block absolute top-1/​2 right-0 bg-white rounded-md transition-transform ease-in-out transform translate-x-full -translate-y-1/​2 group-hover:​translate-x-0 cursor-pointer astro-WRUWT3M6" x-on:click=​"scrollTo(next)​" x-show=​"next !== null" style=​"display:​ none;​">​…​</div>​

#

Uncaught ReferenceError: init is not defined
at eval (eval at safeAsyncFunction (module.esm.js:471:14), <anonymous>:3:16)
at module.esm.js:489:21
at tryCatch (module.esm.js:409:12)
at Function.evaluate (module.esm.js:434:31)
at module.esm.js:2585:35
at Function.<anonymous> (module.esm.js:1174:55)
at flushHandlers (module.esm.js:561:45)
at stopDeferring (module.esm.js:566:5)
at deferHandlingDirectives (module.esm.js:569:3)
at initTree (module.esm.js:787:3)
module.esm.js:420 Uncaught ReferenceError: prev is not defined
at eval (eval at safeAsyncFunction (module.esm.js:471:14), <anonymous>:3:32)
at module.esm.js:489:21
at tryCatch (module.esm.js:409:12)
at module.esm.js:2702:17
at reactiveEffect (module.esm.js:1618:16)
at Object.effect2 [as effect] (module.esm.js:1593:5)
at effect (module.esm.js:48:33)
at wrappedEffect (module.esm.js:64:27)
at Function.<anonymous> (module.esm.js:2702:3)
at flushHandlers (module.esm.js:561:45)
module.esm.js:420 Uncaught ReferenceError: next is not defined
at eval (eval at safeAsyncFunction (module.esm.js:471:14), <anonymous>:3:32)
at module.esm.js:489:21
at tryCatch (module.esm.js:409:12)
at module.esm.js:2702:17
at reactiveEffect (module.esm.js:1618:16)
at Object.effect2 [as effect] (module.esm.js:1593:5)
at effect (module.esm.js:48:33)
at wrappedEffect (module.esm.js:64:27)
at Function.<anonymous> (module.esm.js:2702:3)
at flushHandlers (module.esm.js:561:45)

hexed geode
#

I'd be helpful to have your entire code

#

Because the errors are saying some things are not defined, which is impossible to really diagnose without knowing the rest of your file

rustic pike
hexed geode
#
<div x-data="carousel()" x-init="init()">
  <!-- carousel -->
  <div
    x-ref="container"
  >
    <!-- items container -->
    <div>
      <div><img src="/path/to/image.jpg" /></div>
      <div>
        <div>Content Title</div>
        <time>3/6/2021</time>
      </div>
    </div>
    <div>
      <div><img src="/path/to/image.jpg" /></div>
      <div>
        <div>Content Title</div>
        <time>3/6/2021</time>
      </div>
    </div>
    <div class="w-96 rounded-lg bg-gray-100 overflow-hidden shadow-md">
      <div><img src="/path/to/image.jpg" /></div>
      <div class="px-2 py-3 flex justify-between">
        <div class="text-lg font-semibold">Content Title</div>
        <time>3/6/2021</time>
      </div>
    </div>
    <div>
      <div><img src="/path/to/image.jpg" /></div>
      <div class="px-2 py-3 flex justify-between">
        <div class="text-lg font-semibold">Content Title</div>
        <time>3/6/2021</time>
      </div>
    </div>
    <div>
      <div><img src="/path/to/image.jpg" /></div>
      <div>
        <div>Content Title</div>
        <time>3/6/2021</time>
      </div>
    </div>
  </div>
  <div
    x-on:click="scrollTo(prev)"
    x-show="prev !== null"
  >
    <!-- left navigation -->
    <div>&lt;</div>
  </div>
  <div
    x-on:click="scrollTo(next)"
    x-show="next !== null"
  >
    <!-- right navigation -->
    <div>&gt;</div>
  </div>
</div>

<script is:inline>
  window.carousel = function () {
    return {
      scrollTo(element) {
        const current = this.container;

        if (!current || !element) return;

        const nextScrollPosition =
          element.offsetLeft +
          element.getBoundingClientRect().width / 2 -
          current.getBoundingClientRect().width / 2;

        current.scroll({
          left: nextScrollPosition,
          behavior: "smooth",
        });
      },
    };
  };
</script>
#

Copied version so people don't have to download

#

I think you're missing a lot of code from the blogpost

#

It's complaining that some functions don't exists because well, they don't

#

I'd suggest getting a better understanding of the code you're copying from, so you can more easily debug this kind of errors

rustic pike
#

but the carousel still doesnt work

#

now what do I do -__-

#
  window.carousel = function () {
    return {
      container: null,
      prev: null,
      next: null,
      init() {
        this.container = this.$refs.container;

        this.update();

        this.container.addEventListener("scroll", this.update.bind(this), {
          passive: true,
        });
      },
      update() {
        const rect = this.container.getBoundingClientRect();

        const visibleElements = Array.from(this.container.children).filter(
          (child) => {
            const childRect = child.getBoundingClientRect();

            return childRect.left >= rect.left && childRect.right <= rect.right;
          }
        );

        if (visibleElements.length > 0) {
          this.prev = this.getPrevElement(visibleElements);
          this.next = this.getNextElement(visibleElements);
        }
      },
      getPrevElement(list) {
        const sibling = list[0].previousElementSibling;

        if (sibling instanceof HTMLElement) {
          return sibling;
        }

        return null;
      },
      getNextElement(list) {
        const sibling = list[list.length - 1].nextElementSibling;

        if (sibling instanceof HTMLElement) {
          return sibling;
        }

        return null;
      },
      scrollTo(element) {
        const current = this.container;

        if (!current || !element) return;

        const nextScrollPosition =
          element.offsetLeft +
          element.getBoundingClientRect().width / 2 -
          current.getBoundingClientRect().width / 2;

        current.scroll({
          left: nextScrollPosition,
          behavior: "smooth",
        });
      },
    };
  };
</script>
#

new code

tight bloom
rustic pike
#

Okay it works now I copied your code

#

Grand Salute🫡 @tight bloom for doing such hard work for such a small doubt and helping me out

#

Thank you so muchhh