The carousel spun around, each section moving to the side on its own

One issue I'm facing is that on my page, I have multiple carousel rows. However, when I click on the "next" or "prev" button to navigate through the items in the carousel, it affects all carousels instead of just the one I clicked on.

I've attempted to separate them into partial views so that each JavaScript is executed only within its context, but the problem still persists.

My goal is to be able to navigate to the next and previous items independently of each other.

If possible, I'd like the JavaScript to only target items within the partial view. However, I'm open to considering other solutions as well.

Here is the JavaScript code:

$(document).ready(function () {
    const multipleItemCarousel = document.querySelector('#carouselExample')
    if (window.matchMedia('(min-width: 576px)').matches) {
        const carousel = new bootstrap.Carousel(multipleItemCarousel, {
            interval: false
        })

        var carouselWidth = $('.carousel-inner')[0].scrollWidth;
        var cardWidth = $('.carousel-item').width();

        var scrollPosition = 0;

        $('.carousel-control-next').click(function () {
            if (scrollPosition < carouselWidth - (cardWidth * 4)) {
                scrollPosition += cardWidth;
                $('.carousel-inner').animate(
                    { scrollLeft: scrollPosition },
                    600
                );
            }
        });

        $('.carousel-control-prev').click(function () {
            if (scrollPosition > 0) {
                scrollPosition -= cardWidth;
                $('.carousel-inner').animate(
                    { scrollLeft: scrollPosition },
                    600
                );
            }
        });
    }
    else {
        $(multipleItemCarousel).addClass('slide');
    }

});

This is the HTML code:


<div id="carouselExample" class="carousel">
    <div class="carousel-inner">
        <div class="carousel-item active">
            <div class="card">
                @{
                    var firstCourse = Model.First();

                    <img src="@firstCourse.Image" class="card-img-top" alt="...">
                    <div class="card-body">
                        <h5 class="card-title">@firstCourse.Title</h5>
                        <h6 class="card-subtitle mb-2 text-muted">Card subtitle</h6>
                        <p class="card-text">@firstCourse.Description</p>
                        <a href="#" class="card-link">Card link</a>
                        <a href="#" class="card-link">Another link</a>
                    </div>
                }
            </div>
        </div>
        @foreach (var course in Model.Skip(1))
        {
            <div class="carousel-item">
                <div class="card">
                    <img src="@course.Image" class="card-img-top" alt="...">
                    <div class="card-body">
                        <h5 class="card-title">@course.Title</h5>
                        <h6 class="card-subtitle mb-2 text-muted">Card subtitle</h6>
                        <p class="card-text">@course.Description</p>
                        <a href="#" class="card-link">Card link</a>
                        <a href="#" class="card-link">Another link</a>
                    </div>
                </div>
            </div>
        }
    </div>
    <button class="carousel-control-prev" type="button" data-bs-target="#carouselExample" data-bs-slide="prev">
        <span class="carousel-control-prev-icon" aria-hidden="true"></span>
        <span class="visually-hidden">Previous</span>
    </button>
    <button class="carousel-control-next" type="button" data-bs-target="#carouselExample" data-bs-slide="next">
        <span class="carousel-control-next-icon" aria-hidden="true"></span>
        <span class="visually-hidden">Next</span>
    </button>
</div>

https://i.sstatic.net/c9lxc.jpg

The HTML code has been included for reference.

Answer №1

It is important that each carousel operates within its own scope. The $.find function is used to locate elements that are children of the carousel.

$(document).ready(function() {

  // Assuming #carouselExample is the identifier for all carousels
  const multipleItemCarousels = document.querySelectorAll('#carouselExample')

  multipleItemCarousels.forEach(function(multipleItemCarousel) {

    if (window.matchMedia('(min-width: 576px)').matches) {
      const carousel = new bootstrap.Carousel(multipleItemCarousel, {
        interval: false
      })

      var carouselWidth = $(multipleItemCarousel).find('.carousel-inner')[0].scrollWidth;
      var cardWidth = $(multipleItemCarousel).find('.carousel-item').width();

      var scrollPosition = 0;

      $(multipleItemCarousel).find('.carousel-control-next').click(function() {
        if (scrollPosition < carouselWidth - (cardWidth * 4)) {
          scrollPosition += cardWidth;
          $(multipleItemCarousel).find('.carousel-inner').animate({
              scrollLeft: scrollPosition
            },
            600
          );
        }
      });

      $(multipleItemCarousel).find('.carousel-control-prev').click(function() {
        if (scrollPosition > 0) {
          scrollPosition -= cardWidth;
          $(multipleItemCarousel).find('.carousel-inner').animate({
              scrollLeft: scrollPosition
            },
            600
          );
        }
      });
    } else {
      $(multipleItemCarousel).addClass('slide');
    }
  })
});

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

Transforming identical elements in an arrayt array into distinct elements without eliminating any element in Javascript

Looking for a solution to remove duplicates from an array? You may have come across using track by $index in ng-repeat of angularjs, but you want to stick with a regular ng-repeat. Here's the scenario: Array=[ { name:'john',salary:& ...

Modifying the data of a particular object in my rtk asynchronous thunk

I recently started using rtk and immer. I encountered an issue when trying to update my state with redux. For example, when a user logs in, I store their data in redux with the following structure: data = { "user_profile" : { "name&q ...

Execute asynchronous JavaScript request

When a user types something into the input id=2, an ajax function triggers. Here is the HTML: <input id="2" type="text" onkeyup="posttitulo(this.value)" /> And here is the SCRIPT: function posttitulo(value){ $.post("getdata/posttitulo.php",{p ...

Combine words into lowercase in JavaScript variable

I'm struggling to understand why the data from a form field input is not being stored correctly in a SharePoint column data collection. Currently, when someone inputs a name into a form field, it should automatically populate a SharePoint list: http ...

What is the proper way to structure an Xpath search?

Recently, I've been working with Selenium in QA Test automation. When it comes to selecting/writing Xpath for an element, I've noticed that there are different formats that can be used. For example, protected final String LOGIN_BUTTON_LOCATOR = ...

Stop tooltips from appearing on hyperlinks in Internet Explorer

Is there a solution to disabling the pesky tooltips that appear in the bottom left corner of IE when hovering over links? Alternatively, is there a method to customize the text that appears instead of the default tooltip when hovering over a link (I attem ...

impact on the shape of the region's map

Is it possible to add an effect like a border or opacity when hovering over an area in an image map? I've tried using classes and applying hover effects with borders or opacity, but nothing seems to work as expected. Here's my code: <img src= ...

Utilizing the MEAN stack to establish a connection with a simulated data collection

Currently, I am diving into the world of M.E.A.N stack development. As part of my learning process, I have successfully set up a test page where Angular.js beautifully displays and re-orders data based on search criteria. To challenge myself further, I dec ...

Guide to transferring req.params to a callback function within node.js

I am currently working on a Node.js project using Express. I have been attempting to retrieve data using the NPM request package, utilizing a specific URL and passing an anonymous callback function to handle the resulting JSON file. The code below has bee ...

Ways to retrieve nested data from an object

I have added an object with categories in a database. It displays the price and date of addition. How can I output the date to the console? Currently, in the console, it shows: [ [ { cost: '50$', date: [Object] } ] ]. I need to extract the inform ...

Which NPM packages are necessary for implementing modular Vue components?

While I have experience with traditional multi-page applications created using HTML + JS libraries and server-side rendering (SSR), I am relatively new to modern web development. Currently, I am learning Vue JS (the latest version) through online tutorials ...

Ajax alert: The index 'id' is not defined

I'm currently learning PHP and scripting, but I am encountering some difficulties when it comes to sending information to PHP. I would appreciate any help you can offer. Thank you for your assistance. Here is the issue at hand: Error Message: Noti ...

I seem to be experiencing a depletion of my cache... (Objects are mysteriously disappearing from my cache)

Currently in the process of developing a website using ASP.NET Webforms.. I've implemented caching strategically with High / Normal / Low priority levels, specifying durations of 2 weeks, 1 week, and 4 hours respectively. To aid in debugging, I disp ...

Utilize socket communication with node.js to monitor and identify user

I'm attempting to find a method to unsubscribe from a Redis channel when the user navigates to another page within our website. I have attempted to detect a disconnect socket event when the user clicks on a link, but unfortunately, the event is never ...

Individuals have the capability to utilize .php as an image extension

It seems that someone is able to use any type of extension as long as they add .png at the end of the link. is currently being used, causing users on my website to log out when visiting the homepage. I tried to stop this issue, but unfortunately, my sol ...

What is the best way to categorize a collection of objects within a string based on their distinct properties?

I am working with an array of hundreds of objects in JavaScript, each object follows this structure : object1 = { objectClass : Car, parentClass : Vehicle, name : BMW } object2 = { objectClass : Bicycle, parentClass : Vehicle, name : Giant } object3 = { ob ...

Adjusting the arrangement of elements based on the size of the screen

Two floating <div>'s are styled with classes .a and .b. Both <div>'s are floated to the left, each taking up 50% of the width, aligning them horizontally. On smaller screens, I want both <div>'s to be aligned vertically. ...

Repetitive NodeJS event triggers within Electron-React application causing unexpected behavior

In my custom software package (referred to as PACKAGE_A), I have implemented various automated tasks using a node script. This package includes a Notifier module that creates and exports an EventEmitter. (The entire project is structured as a Monorepo) co ...

Adding two input values using jQuery

Here is the function compute() that I am working with: function compute() { if ($('input[name=type]:checked').val() != undefined) { var a = $('input[name=service_price]').val(); var b = $('input[name=modem_pric ...

How can you configure fancybox3 to open exclusively on a double-click?

Looking for a solution to open a fancybox gallery with a double click on a grid of sortable images. The goal is to be able to focus on an image with a single click, allowing for sorting using keyboard commands rather than drag and drop. I attempted to use ...