Stop the jQuery custom slide animation when there are no more items to display

I have designed a unique slider for users to view the work process https://i.sstatic.net/FLYne.png

When a user clicks the button, the slider will move left or right depending on the button clicked. However, if the user clicks multiple times, the slider may move too far and leave a large gap as shown in the image below https://i.sstatic.net/6vIXV.png

Is there a way to make the slider stop when there are no more items behind it, like in picture 3?

https://i.sstatic.net/ptZCO.png

jQuery(document).ready(function($){
   var direction = 1;
   
   const slideSec = document.querySelector('.movingsec .container');
   
   const slideItem = document.querySelectorAll('.movingsec .image-box');
   
   var maxItem = slideItem.length;
   
   $('.btnPrev').click(function(){
       direction = 0;
       runSlide(direction);
   });
   
   $('.btnNext').click(function(){
      direction = 1;
      runSlide(direction);
   });
   
   var current = 0;
   
   function runSlide(direction){
       if(direction === 1){
           current = current + 1;
           if(current === maxItem){
               current = maxItem - 1;
           }
       }
       
       if(direction === 0){
           current = current - 1;
           if(current < 0){
               current = 0;
           }
       }
       
       var destination = current * 215;
       $(slideSec).css('transform','translateX(-'+destination+'px)');
   }
});

The snippet above showcases the code I have developed for this slider.

Answer №1

Here is a potential solution that may work for you, depending on your HTML and CSS:

jQuery(document).ready(function($) {
    const adjust = true;

    const section = document.querySelector('.movingsec .container');
    const items = document.querySelectorAll('.movingsec .image-box');
    const container = $(section).parent();
      
    const maxItems = items.length;
    const itemWidth = $(items[0]).outerWidth(true);

    $('.btnPrev').click(function() {
        moveSlide(0);
    });
    $('.btnNext').click(function() {
        moveSlide(1);
    });

    var currentSlide = 0;

    function moveSlide(direction) {
        var adjustLast = 0;
        if (direction === 1) {
            const containerWidth = container.width();
            const visibleItems = parseInt(containerWidth / itemWidth);
            const hiddenItems = maxItems - visibleItems - currentSlide;
            if (hiddenItems <= 0) {
                return;
            }
            adjustLast = adjust && hiddenItems == 1 ? containerWidth % itemWidth : 0;
            currentSlide = currentSlide + 1;
        }
        if (direction === 0) {
            if (currentSlide === 0) {
                return;
            }
            currentSlide = currentSlide - 1;
        }
        const destination = currentSlide * itemWidth - adjustLast;
        $(section).css('transform', 'translateX(-' + destination + 'px)');
    }
});

This solution is designed to accommodate dynamic container width and static slide width with margins.

To add extra space after the last slide, change adjust to false.

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

Utilizing jPlayer to play music files uploaded using Paperclip in a Ruby on Rails application with the help of jQuery

Just wanted to say thanks in advance for any help. Currently, I am storing songs in a filesystem using Paperclip and attempting to play them with jPlayer. Despite following all the necessary steps, I am unable to get the audio to play when clicking on a ...

Experiencing a hiccup in your jQuery animation?

Click here to access the fiddle demonstrating the issue. A situation arises where a span with display: inline-block houses another span that is being slowly hidden. The container span unexpectedly shifts back to its original position once the hiding proces ...

Identifying on-the-fly adjustments in form input

I am facing an issue where I want to trigger an action when the inputs in my dynamically added form are changed, but unfortunately, it is not working as expected. The HTML code for embedding my form via iframe is shown below: <iframe onload="javascript ...

The secrets behind the seamless, fluid layout of this website

Upon exploring the website www.emblematiq.com, I noticed that it features a fluid/liquid layout. Despite analyzing the code, I am unable to decipher how this effect is achieved. The layout appears to be fixed width with the canvas element set at 1180px. D ...

Can Highchart dynamically adjust color choices based on the quantity of data points available?

I am trying to figure out how to import a specific color palette into my column graph. I want to use different color palettes based on the number of data points in my graph - for 3 or fewer points, I want to use the top row colors, for 4 points I want to u ...

Utilize the angularJS filter to emphasize the search text within the search results

I have a search box that filters results displayed on the screen. I am using a filter called 'startWith' for this purpose. Now, I need to implement a feature where the search text is highlighted among the search results in angularJS. For example ...

Is it possible to access a component's function from outside an ng-repeat in Angular 1.5?

Recently delved into learning Angular 1.5 components and testing out some fresh concepts, however, I'm struggling to wrap my head around this particular issue: Here's the code snippet from my Main: angular.module('myapp',[]) .contr ...

Methods to verify if an array contains a particular string within a PUG template

I'm currently working with NodeJS using Express and the PUG view engine. My goal is to determine whether an array includes a specific string. I've experimented with JavaScript's built-in methods like: array.includes(str) array.indexOf(str) ...

Is it possible to devise a universal click handler in TypeScript that will consistently execute after all other click handlers?

In my ReactJS based application written in TypeScript, we have implemented various click handlers. Different teams contribute to the application and can add their own handlers as well. The challenge we face is ensuring that a specific global click handler ...

Utilizing the click event with a Bootstrap modal: A guide

I have a PHP script that generates multiple Bootstrap modals, and I want to be able to modify some input fields when the "save changes" button is clicked. The ModalIDs generated are in the format "ModalID0000". However, nothing happens when I click on the ...

Are there any solutions for the malfunctioning v8 date parser?

The V8 Date parsing functionality is not functioning properly: > new Date('asd qw 101') Sat Jan 01 101 00:00:00 GMT+0100 (CET) I have attempted to use a delicate regular expression like the following: \d{1,2} (jan|feb|mar|may|jun|jul|a ...

Fixing the reinitialization of a data table

I've been grappling with this issue for quite some time now (exactly 5 days) and I keep encountering the following error. DataTables is throwing a warning: table id=activities-table - Cannot reinitialize DataTable. For more details regarding this ...

Stop all animations in JS and CSS

Looking for a way to halt all CSS and JavaScript animations, including canvas and webGL effects, on a specific webpage. Some animations can cause slow performance on certain browsers like Opera and Firefox, so I'm seeking a code snippet or guidance o ...

Middle-Click JavaScript Action

On the website I'm currently working on, there is a button that uses a sprite sheet animation and therefore needs to be set as a background image. I want the button to have a slight delay when clicked, so the animation can play before redirecting to a ...

Effective methods for importing components in VueJS 2.0

As a newcomer to VueJs, I have a question regarding the best practice for importing components in a Vue Template Project. I currently have some components that are used in multiple views. After downloading an admin template, I noticed that the samples alwa ...

Using ParsleyJS to activate on form fields dynamically created through AJAX requests

My issue arises from having a form that, when a click event occurs, sends an ajax request to another URL. The response from the server is then appended (a series of form inputs) to the end of the current form. The dilemma I am facing is that Parsley, whic ...

What is the best way to apply a hover rule to a CSS class in order to change the color of a specific row when hovering in

I have managed to successfully apply a classname and add color to a specific row in my react-table. However, I am facing difficulty in adding a hover rule to this className to change the color when I hover over the row. Can someone guide me on how to apply ...

Unresponsive Webpage

I am currently managing Facebook Ads for a client, but I have encountered an issue with their website not being responsive on mobile devices. While I have some knowledge of basic HTML & CSS, I am uncertain about how to address this particular problem. The ...

The use of async components in Vue.js with named imports

I understand how to dynamically load components asynchronously in Vue. For example, instead of importing MyComponent directly: import MyComponent from '@/components/MyComponent' export default { components: { MyComponent } } We can use ...

Issue with the statement not being recognized for counting the space bar

I created a counter but I'm having trouble incorporating if statements For example: if (hits == 1) {alert("hello world1")} if (hits == 2) {alert("hello world2")} if (hits == 3) {alert("hello world3")} if (hits == 4) {alert("hello world4")} This is t ...