The Carousel feature functions properly with 3 or more slides, but malfunctions when there are only 2 slides present

After implementing a minimal carousel, I discovered that it functions perfectly with 3 or more slides. However, as soon as I remove some slides, issues start to arise. Some of the problems I encountered include:

  1. The sliding animation is removed on 'next'
  2. The divs begin to flicker
  3. The animation breaks entirely

I attempted some solutions involving .clone() on the initial slide and then using .append() to add it to the end of the container. While this approach somewhat worked, it usually only allowed for one rotation before getting stuck on slide2.

Below is the logic I developed for handling clicks on the prev/next buttons:

var before_clone = $(elm + ':first').clone();
var after_clone = $(elm + ':last').clone();
$('#buttons a').click(function(e) {
    //slide the item
    if (container.is(':animated')) {
        return false;
    }
    if (e.target.id == previous) {
        container.stop().animate({
            'left': 0
        }, 1500, function() {
            //container.find(elm + ':first').before(container.find(elm + ':last'));
            container.append(after_clone);
            container.find(elm + ':last');
            resetSlides();
        });
    }
    if (e.target.id == next) {
        container.stop().animate({
            'left': item_width * -1
        }, 1500, function() {
            //container.find(elm + ':last').after(container.find(elm + ':first'));
            container.append(before_clone);
            container.find(elm + ':first');
            resetSlides();
        });
    }
    //cancel the link behavior            
    return false;
});

And here is the logic I implemented for managing automatic animations:

function rotate() {
    $('#next').click();
      container.append(before_clone);
      container.append(after_clone)
}

Here are two Fiddles that may help diagnose my problem:

Link to current attempt

Link to original code (ensure to remove/comment out 2 of the lis)

If you have any insights or solutions to offer, I would greatly appreciate your assistance in resolving this issue! Thank you!

Answer №1

Check out this code snippet.

I made a tweak to your next as shown below:

if (e.target.id == next) {
    container.find(elm + ':last').after(container.find(elm + ':first'));
    container.css({
        'left': 0
    });
    container.stop().animate({
        'left': item_width * -1
    }, 1500, function () {
        resetSlides();
    });
}

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

What is the best method for retrieving all input fields within a form that are of the types text, password, file, textarea, and selectbox?

Is there a way to retrieve all input fields of specific types within a form using jQuery? jQuery("#signup-form").find('input').each(function(index, element) { }); I am aware that I can target text boxes with: jQuery("#signup-form").find(&apos ...

Tips for receiving user input with custom values and assigning them to variables through multiple selection criteria using Jquery

I am encountering an issue with a form that contains multiple selection blocks. I am attempting to extract the values of each block criteria on click in order to send it to a database. However, every time I click on a block, my script retrieves all the val ...

I have the latitude and longitude for both the shop and user, and I am looking to display a list of shops in order based

Currently, I have the latitude and longitude for both my shop and the user. My objective is to display a list of shops that fall within the geographic area between the user's location and the shop's coordinates using Sequelize ORM. Can you provid ...

"Encountering an issue with supabase.auth.getUser() when implementing a vue-router route guard

My Vue application project involves integrating Supabase authentication. In one of the route guards within the router file, I used supabase.auth.getUser() to determine the user's login status and control the execution flow based on that condition: // ...

Developing pledges in AngularJS

I am currently working on implementing a promise in Angular using the $q service to retrieve an object from a web service. The unique aspect of this implementation is that if the object is already cached, it should be returned without making a call to the ...

Change a portion of the CSS background-image URL using vanilla JavaScript for a set of pictures

My current code successfully updates part of an src URL for regular images. let svgz = document.querySelectorAll(".svg"); for (let i = 0; i < svgz.length; i++) { svgz[i].src = svgz[i].src.replace("light", "dark"); } Now, ...

Is it feasible to invert the order of arguments in async.apply?

According to the async documentation: apply(function, arguments..) Creates a function continuation with certain arguments already applied. This can be useful when combined with other control flow functions. Any additional arguments passed to the returned ...

Injecting Custom HTML Tag through JavaScript on Page Load in Google Tag Manager

When attempting to inject events into the data layer upon loading DOM pages on my website, I encountered an issue. Since I lack access to the website code and developers are reluctant to make additions, I decided to implement this through a custom HTML tag ...

efficiency of this algorithm

function checkSubset(array1, array2) { const set1 = new Set(array1); const set2 = new Set(array2); for (const element of set2) { if (!set1.has(element)) { return false; } } return true; } Can we consid ...

ACL - Utilize ACL in conjunction with the passport authentication system

I am experimenting with node_acl in combination with passport-local. Unfortunately, I am facing an issue when trying to secure the route for the admin-user '/admin', as it keeps redirecting me to the /login page. Below is a simplified version of ...

How to perfectly align an element within a div using Bootstrap

Utilizing bootstrap here. Currently trying to center the h1 element within the div, but so far I have been unsuccessful. It consistently remains aligned to the left. Attempts have included using bootstrap's center-block helper class, as well as the fl ...

Form tags are closing automatically on their own

Currently experiencing an issue where a form tag is mysteriously closing on its own. In the process of troubleshooting and pinpointing the root cause of this unexpected behavior. Inside the table structure due to Netsuite usage, which complicates the debu ...

What is the best way for library creators to indicate to VSCode which suggested "import" is the correct one?

As a library creator, I have noticed that VSCode often suggests incorrect imports to users. For instance, VSCode typically suggests the following import: import useTranslation from 'next-translate/lib/esm/useTranslation' However, the correct im ...

Creating a cascade of falling balls with a single click: Here's how!

I'm currently working on a project where I have a ball dropping from the cursor location and redropping when the cursor moves to another position. However, I want to be able to create a new ball every time I click the mouse. I attempted the following ...

An error occurred while attempting to retrieve data from a JSONArray

I have been working on creating a phonegap plugin for Android where I am returning a JSONArray using callBackContext.sendPluginResult(result);. Below is the code snippet demonstrating how I am constructing the JSONArray: private JSONArray makeJsonObject(S ...

Challenge with PHP mail function in sending emails

I run a website and have a "Contact" section where users can fill out a form to reach me. The form is a basic one with its action being a php page. Here is the php code: $to = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4 ...

Basic inquiry sent to a Symfony2 server

I am currently working on integrating the infinite scroll feature into Symfony2. Controller: public function indexAction(Request $request) { if (!$request->isXmlHttpRequest()) { return $this->render( 'UsuarioBundle:De ...

The undefined dispatch function issue occurs when trying to pass parameters from a child component to React

There is an action that needs to be handled. It involves saving a new task with its name and description through an API call. export const saveNewTask = (taskName, taskDescription) => async dispatch => { console.log(taskName, taskDescription); c ...

How to style an HTML table with just a bottom border

Is there a way to recreate the Staff Directory section of this page using only HTML, without having to rely on CSS and Javascript? Specifically, I want to create a table with only bottom borders/dividers for each line. Any suggestions on how to achieve thi ...

Error message: Unable to access the state property of an undefined object

I've been attempting to integrate a react sticky header into my stepper component. However, I've encountered an issue where it doesn't render when added inside my App.js file. As a result, I've started debugging the code within App.js ...