The carousel's slides don't behave properly when swiping or using the slider controls (next/prev)

I have recently completed the construction of a carousel with swipe/touch functionality and control buttons for previous and next slides. However, I am facing an issue with the behavior of the carousel as it seems to be sliding by 2 or 3 instead of one at a time. Here is a snippet of the code I have been working on.

I am also encountering problems with making the carousel responsive.

function fCarousel() {
  // var activeSlide = 0;
  // $('.faculty-carousel').attr('data-slide', '0');

  var viewPortSize         = $(window).width(),
      facultyPanel         = $('.faculty-carousel .faculty-items li'),
      profileCount         = facultyPanel.length,
      activeSlide          = 0,
      carousel             = $('.faculty-carousel .faculty-items');

  $('.faculty-carousel').attr('data-slide', '0');

  //Set Panel Size based on viewport

  if (viewPortSize <= 1920 ) {
      var profilePanelSize = viewPortSize / 5
  }

  if (viewPortSize < 1024 ) {
      var profilePanelSize = viewPortSize / 4
  }

  if (viewPortSize < 768 ) {
      var profilePanelSize = viewPortSize / 3
  } 

  if (viewPortSize < 480 ) {
      var profilePanelSize = viewPortSize
  }

  carousel.outerWidth( profilePanelSize * profileCount );
  facultyPanel.outerWidth(profilePanelSize);
  carousel.css('transform', 'translateX(' + 0 + '% )');

  $('.prev').on('click', function(e) {
      event.stopPropagation();

    var carouselWrapper     = $(this).closest('.faculty-carousel'),
        facultyProfilePanel = carouselWrapper.find('.faculty-items li'),
        facultyProfileCount = facultyProfilePanel.length,
        viewPortSize        = $(window).width(),
        carousel            = carouselWrapper.find('.faculty-items'),
        position            = 0,
        currentSlide        = parseInt(carouselWrapper.attr('data-slide'));

      // Check if data-slide attribute is greater than 0
      if (currentSlide > 0) {
          // Decrement current slide
          currentSlide--;
          // Assign CSS position to clicked slider
          var transformPercentage = -1 * currentSlide / facultyProfileCount * 100;
          carousel.css('transform', 'translateX(' + transformPercentage + '% )');
          // Update data-slide attribute
          carouselWrapper.attr('data-slide', currentSlide);
          activeSlide = currentSlide;
      }
  });

  // More code here

}

$(document).ready(function() {
  fCarousel();
})

$(window).on('resize', function(){
  fCarousel();
})
/* Your CSS code here */
<!doctype html>
<html>
<head>
<title>Carousel</title>
<link rel="stylesheet" href="style.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.8/hammer.min.js"></script>
</head>
<body>
  <!-- Your HTML code here -->
</body>
</html>

Answer №1

When I initially rushed my first answer, I provided a clear JavaScript representation of how modern Carousels typically function. The implementation details are up to you if you decide to utilize it.

Here's a detailed explanation of the JavaScript logic:

// Index all Carousel
for (var i = 0; i < document.getElementsByClassName("carousel").length; i++) {
    // Create a container for all the slides
    document.getElementsByClassName("carousel")[i].innerHTML = (
        '<div class="slides-container">' +
            document.getElementsByClassName("carousel")[i].innerHTML +
        '</div>'
    );
    
    // More JavaScript code could go here...

This section covers the core functionality of the Carousel using JavaScript, allowing you to customize its behavior further based on your requirements.

For those interested in exploring innovative JavaScript projects, feel free to check out a library I've been developing: https://github.com/LapysDev/LapysJS.

Answer №2

If you want to enhance your galleries, consider using Slick. It provides a better amount of features compared to other gallery options. Check out Slick here

Answer №3

To address the sliding issue, I made some modifications to both the CSS and JS code. The changes ensure that the slide moves smoothly on one slide and also account for smaller screen resolutions.

Updated JS Code:

Revised CSS Styles:

The HTML remains unchanged, so you can continue using the same existing HTML code. If you have any further questions or issues, feel free to reach out. Best regards.

Answer №4

For efficiently setting and getting values in a group of elements, the recommended approach is to utilize the .map() method. You can view the detailed solution in 50 lines on CodePen (view on CodePen):

$(".faculty-carousel").map(function() {
  // Utilize that to reference child nodes within each carousel object instance
  var that = $(this),
    slides = that.find(".faculty-items li"),
    carousel = that.find(".faculty-items"),
    prevBtn = that.find(".prev"),
    nextBtn = that.find(".next"),
    slideLen = slides.length,
    slideCount = slideLen - 1;

  // Define starting point for carousel movements by adding .is-active class to activeSlide
  slides.first().addClass("is-active");

  // Shift based on user click with optional direction argument
  var shiftCarousel = function(direction) {
    var target = that.find(".is-active");
    var currentSlide = target.attr("data-slide");
    if (direction === "left" && currentSlide > 0) {
      currentSlide--;
      target.removeClass("is-active").prev().addClass("is-active");
    }
    if (direction === "right" && currentSlide < slideCount) {
      currentSlide++;
      target.removeClass("is-active").next().addClass("is-active");
    }
    var transformPercentage = -1 * currentSlide / slideLen * 100;
    carousel.css("transform", "translateX(" + transformPercentage + "% )");
  };

  var x = 0;

  // Determine position of each slide and store it as an HTML attribute
  slides.each(function() {
    $(this).attr("data-slide", "" + x++ + "");
    $(this).click(function() {
      $(this).addClass("is-active").siblings().removeClass("is-active");
      
      // Call shiftCarousel() without any parameter
      shiftCarousel();
    });
  });

  // Invoke shiftCarousel() with specified parameter
  prevBtn.on("click", function() {
    shiftCarousel("left");
  });
  nextBtn.on("click", function() {
    shiftCarousel("right");
  });

  // For handling mobile events, refer to Hammer API or native touchstart, touchcancel events
});

In this scenario, sticking with jQuery is more advisable. Oluwafunmito's solution suggests using innerHTML, which is a viable technique in vanilla JS. However, bear in mind that innerHTML may inadvertently expose your website to XSS attacks and should be used cautiously.

Answer №5

Experience the power of Swiper, the cutting-edge mobile touch slider that boasts hardware accelerated transitions and exceptional native functionality.

Answer №6

If you're struggling with your code, here's a fully functional carousel code using bootstrap and JavaScript that might provide some insights on where your program needs improvement. Take a look and see if it helps in debugging your code.

<div id="mycarousel" class="carousel slide" data-interval="3000" data-ride="carousel">
            <!-- Indicators -->
<ol class="carousel-indicators">
    <li data-target="#mycarousel" data-slide-to="0" class="active"></li>
    <li data-target="#mycarousel" data-slide-to="1"></li>
    <li data-target="#mycarousel" data-slide-to="2"></li>
</ol>
            <!-- Wrapper for slides -->
<div class="carousel-inner" role="listbox">
    <div class="item active">
        <img class="img-responsive"
         src="img/uthappizza.png" alt="Uthappizza">
        <div class="carousel-caption">
        <h2>Uthappizza  <span class="label label-danger">Hot</span> <span class="badge">$4.99</span></h2>
        <p>A unique combination of Indian Uthappam (pancake) and
          Italian pizza, topped with Cerignola olives, ripe vine
          cherry tomatoes, Vidalia onion, Guntur chillies and
          Buffalo Paneer.</p>
        <p><a class="btn btn-primary btn-xs" href="#">More &raquo;</a></p>
        </div>
    </div>
    <div class="item">
      <img class="media-object img-thumbnail"
       src="img/buffet.png" alt="Buffet">
        <div class="carousel-caption">
          <h2>Weekend Grand Buffet <span class="label label-danger">New</span> </h2>
          <p>Featuring mouthwatering combinations with a choice of five different salads,
             six enticing appetizers, six main entrees and five choicest desserts.
              Free flowing bubbly and soft drinks. All for just $19.99 per person</p>
          <p><a class="btn btn-primary btn-xs" href="#">More &raquo;</a></p>
          </div>
    </div>
    <div class="item">
      <img class="media-object img-thumbnail"
       src="img/alberto.png" alt="Alberto Somayya">
        <div class="carousel-caption">
          <h2 >Alberto Somayya</h2>
          <h4>Executive Chef</h4>
          <p>Award winning three-star Michelin chef with wide
           International experience having worked closely with
           whos-who in the culinary world, he specializes in
            creating mouthwatering Indo-Italian fusion experiences.
           </p>
           <p><a class="btn btn-primary btn-xs" href="#">More &raquo;</a></p>

        </div>
    </div>
    <!-- Controls -->
<a class="left carousel-control" href="#mycarousel" role="button" data-slide="prev">
    <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#mycarousel" role="button" data-slide="next">
    <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
    <span class="sr-only">Next</span>

</a>
<div class="btn-group" id="carouselButtons">
    <button class="btn btn-danger btn-sm" id="carousel-pause">
      <span class="fa fa-pause" aria-hidden="true"></span>
    </button>
    <button class="btn btn-danger btn-sm" id="carousel-play">
      <span class="fa fa-play" aria-hidden="true"></span>
    </button>
</div>

</div>
          </div>

JavaScript

<script>
    $('.carousel').carousel('pause')
</script>
<script>
    $(".btn-group > .btn").click(function(){
    $(this).addClass("active").siblings().removeClass("active");
    });
</script>
<script>
$(document).ready(function(){
    //$("#mycarousel").carousel( { interval: 2000 } );
                  $("#carousel-pause").click(function(){
        $("#mycarousel").carousel('pause');
    });
                $("#carousel-play").click(function(){
        $("#mycarousel").carousel('cycle');
    });
  });
</script>

Credits: Coursera

Answer №7

Instead of applying the .each method to all slides in every carousel, focus on binding your function (along with the included pan) specifically to $('.faculty-carousel').each. This will streamline the process and optimize performance.

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

Checking if the Cursor is Currently Positioned on a Chart Element in Word Addin/OfficeJS

I am looking for a way to determine if the document cursor is currently positioned inside of a Chart element using the Microsoft Word API. My current application can successfully insert text, but when I attempt to insert text into the Chart title, it ends ...

Retrieve information from various tables in a SQLite database using Node.js

Is there a method to retrieve all data from multiple tables in a database? Currently, I have managed to fetch all data from a single table: router.get('/', function (req, res, next) { db.serialize(function () { db.all('SELECT id, name ...

Guidelines on launching an ionic 4 modal using routes

How can I open a modal using routes? I attempted the following approach, but it did not work as expected: ngOnInit() { this.launchModal(); } async launchModal() { const modal = await this.modalController.create({ component: AuthPasswordR ...

Changing a JavaScript command into a text representation

Currently, I have an array stored in a variable as shown below: arr = [1, 2, 3] Is there a way to convert this array statement into a string like this? newArr = "arr = [1, 2, 3]" ...

Unable to execute PHP alongside a JavaScript event listener

Using PHP, I am creating a canvas for writing and the text output will appear in a textarea (handled by other functions). There are additional input tags like a title to gather user input. The values from these input tags (title and textarea) will be submi ...

The request included an unsupported media type of "text/plain;charset=UTF-8". This caused an error in the NextJS API when interacting with Django Rest Framework

Currently diving into the world of web development, I am endeavoring to construct a website utilizing NextJS and Django Rest Framework. While NextJS effectively proxies API endpoints for retrieving data, I find myself grappling with making it work for a PO ...

Exploring discrepancies between two tables with the power of Javascript

const firstTable = document.getElementById('table_1') const secondTable = document.getElementById('table_2') const rows1 = firstTable.rows const rows2 = secondTable.rows for (let i = 0; i < rows1.length; i++) { for (let x in rows ...

Leaving the pipeline of route-specific middleware in Express/Node.js

My implementation involves a sequence of "route specific middleware" for this particular route: var express = require('express'); var server = express(); var mw1 = function(req, resp, next) { //perform actions if (suc ...

What is the best way to implement the Snackbar functionality within a class-based component?

My snackbar codes are not working as expected when I click the "confirm" button. I want the snackbar to appear after clicking the button. Most examples I've seen use functional components, so how can I get the Snackbar to work properly in a class comp ...

HTML: arranged <pre> with fixed positioning

I currently have a centered column of text with a fixed width. However, I am looking to break that fixed width for certain tags like <pre> so that they can fill the full screen width while maintaining flow with the rest of the text. My CSS snippet s ...

Omit the tag from the submission section

Currently, I am utilizing a <p> tag as a submit button/area by setting a specific id in jquery. <p id="xyz"></p> My requirement is to insert an input field inside this <p> tag to include a particular value that will be submitted u ...

Transition/transform/translate3d in CSS3 may lead to significant flickering on the initial or final "frame" of the transition (specifically on an iPad)

Hello everyone, I am currently developing a web application specifically for the iPad and I have implemented a CSS3 transition to animate a div, moving it from left to right. Here is the structure of my class: .mover { -webkit-transition:all 0.4s ea ...

"Switching out elements and tallying up values in an array

I am working with an array of identifiers for items var names = ['1','2', '1', '3']; Using these ids, I send an ajax request to retrieve the name associated with each id and replace it accordingly; var names = [ ...

Issues with jQuery AJAX functionality

I am in the process of incorporating some ajax functionality into my php website. I have a good understanding of jQuery, but for some reason, the value returned is always empty when I try to alert() it. Below is the code snippet that I am using: PHP: if( ...

Can anyone provide guidance on how to simulate a click on a JavaScript action for an iPhone?

I am attempting to trigger a click on a "javascript:void(0)" link so that I can retrieve HTML data within the script. Can someone advise me on how to achieve this without using illegal APIs like UITouchEvent, as I only work with NSUrl? Thank you in advan ...

Is it possible to bypass the confirmation page when submitting Google Form data?

Is there a way to bypass the confirmation page that appears after submitting a form? What I would like is for the form to simply refresh with empty data fields and display a message saying "your data has been submitted" along with the submitted data appea ...

Populate several input boxes with data derived from a single input field

I am facing an issue with three textboxes in my project. When I type something in the first textbox, the value is sent to state.jsp and displayed using out.println(firsttextboxvalue); on the response ID of the second textbox. However, I want to populate th ...

My React application did not display properly after deploying it on GitHub Pages

I attempted to deploy my React app on GitHub Pages, but unfortunately it did not work as expected. When I tried to access the link, all I got was a blank page. Can anyone help me with a solution? Your assistance is much appreciated! Here's a snippet ...

Having Trouble Using Fetch API with ASP.NET Core 2 Controllers that Require Authorization

I have the following code on the client side: fetch("/music/index", { headers: { "Content-Type": "application/json" } }) .then(response => { if (!response.ok) { throw response; } return response.json(); }) ...

Arrange your grid system with Bootstrap Vue

There is a dataset retrieved from an API, and each item will be displayed within a div using a v-for loop. The desired layout for the grid of divs is as follows: [-- item 1 --][-- item-2 --] [-- item 3 --][-- item-4 --] [-- item 5 --][-- item-6 --] [-- ite ...