Search code examples
javascripthtmlcss

JavaScript slider not scrolling automatically from left to right


I'm trying to create a slider that automatically scrolls from left to right when the user reaches the end of the current item. I've tried using the following JavaScript code, but it's not working as expected:

console.log("Slider");



// Get the slider container element
const sliderContainer = document.querySelector('.slider-container');

// Get all slider item elements
const sliderItems = document.querySelectorAll('.slider-item');

// Add event listener to the slider container
sliderContainer.addEventListener('scroll', () => {
  // Get the current scroll position
  const scrollPosition = sliderContainer.scrollLeft;

  // Loop through each slider item
  sliderItems.forEach((item, index) => {
    // Check if the item is in view
    if (scrollPosition >= item.offsetLeft && scrollPosition < item.offsetLeft + item.offsetWidth) {
      // Add the active class to the item
      item.classList.add('active');
    } else {
      // Remove the active class from the item
      item.classList.remove('active');
    }

    // Check if we've reached the end of the current item
    if (scrollPosition + sliderContainer.offsetWidth >= item.offsetLeft + item.offsetWidth) {
      // Automatically scroll to the next item
      sliderContainer.scrollLeft = item.offsetLeft + item.offsetWidth;
    }
  });
});

The slider container has a horizontal scrollbar, and I want it to automatically scroll to the next item when the user reaches the end of the current item. However, the slider is not scrolling automatically, and I'm not seeing any errors in the console.

I've tried modifying the condition to check if we've reached the end of the current item, but it's still not working. Can anyone help me identify the issue or provide a solution to achieve the desired behavior?

html

<div class="slider-item">

            <img src="{% static './assets/images/banner-1.jpg' %}" alt="women's latest fashion sale" class="banner-img">

            <div class="banner-content">

              <p class="banner-subtitle">Trending item</p>

              <h2 class="banner-title">Women's latest fashion sale</h2>

              <p class="banner-text">
                starting at &dollar; <b>20</b>.00
              </p>

              <a href="#" class="banner-btn">Shop now</a>

            </div>

          </div>

          <div class="slider-item">

            <img src="{% static './assets/images/banner-2.jpg' %}" alt="modern sunglasses" class="banner-img">

            <div class="banner-content">

              <p class="banner-subtitle">Trending accessories</p>

              <h2 class="banner-title">Modern sunglasses</h2>

              <p class="banner-text">
                starting at &dollar; <b>15</b>.00
              </p>

              <a href="#" class="banner-btn">Shop now</a>

            </div>

          </div>

          <div class="slider-item">

            <img src="{% static './assets/images/banner-3.jpg' %}" alt="new fashion summer sale" class="banner-img">

            <div class="banner-content">

              <p class="banner-subtitle">Sale Offer</p>

              <h2 class="banner-title">New fashion summer sale</h2>

              <p class="banner-text">
                starting at &dollar; <b>29</b>.99
              </p>

              <a href="#" class="banner-btn">Shop now</a>

            </div>

          </div>

css:

.slider-container {
  display: flex;
  align-items: center;
  gap: 10px;
  border-radius: var(--border-radius-md);
  overflow-x: auto; /* Add this line */
  scroll-snap-type: inline mandatory;
  overscroll-behavior-inline: contain;
}

.slider-item {
  position: relative;
  min-width: 100%;
  max-height: 450px;
  aspect-ratio: 1 / 1;
  border-radius: var(--border-radius-md);
  overflow: hidden;
  scroll-snap-align: start;
}

.slider-item .banner-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  object-position: right;
}

Additional details:

  1. I want the slider to automatically scroll to the next item when the user reaches the end of the current item.
  2. I'm not sure if there are any specific browser or device requirements that might be affecting the behavior.

Solution

  • Updated JavaScript Code:

    document.addEventListener("DOMContentLoaded", function () {
        console.log("Slider");
    
        // Get the slider container element
        const sliderContainer = document.querySelector('.slider-container');
    
        // Ensure sliderContainer is found
        if (!sliderContainer) {
            console.error("Slider container not found.");
            return;
        }
    
        // Get all slider item elements
        const sliderItems = document.querySelectorAll('.slider-item');
    
        // Variable to keep track of the current item index
        let currentIndex = 0;
    
        // Function to scroll to the next item
        function scrollToNextItem() {
            // Increment the current index
            currentIndex = (currentIndex + 1) % sliderItems.length;
    
            // Scroll to the next item
            sliderItems[currentIndex].scrollIntoView({ behavior: 'smooth' });
    
            // Automatically scroll to the next item after a delay
            setTimeout(scrollToNextItem, 3000); // Adjust the delay as needed
        }
    
        // Start the automatic scroll
        scrollToNextItem();
    
        sliderContainer.addEventListener('scroll', () => {
            // Get the current scroll position
            const scrollPosition = sliderContainer.scrollLeft;
    
            // Loop through each slider item
            sliderItems.forEach((item, index) => {
                // Check if the item is in view
                if (scrollPosition >= item.offsetLeft && scrollPosition < item.offsetLeft + item.offsetWidth) {
                    // Update the current index to the visible item
                    currentIndex = index;
                }
            });
        });
    });