How can I make my slider perfectly accommodate the component inside?

I am working on developing a slider similar to the McDonald's one:

The main goal for my slider is to adjust to the container element size, so that when the user clicks the left or right buttons, the slider smoothly moves to the corresponding direction and wraps back around when reaching the boundaries. However, I'm facing inconsistencies in my slider behavior - it doesn't respond correctly to events triggering and the state management seems buggy. I'm looking for ways to enhance my application.

My current slider lacks fluent functionality. You can see the demo here (notice script bugs on StackOverflow but works fine on JSFiddle):

Updated code snippets with modifications...
Updated CSS styling for better performance...
Updated script sources for React integration...

If you have any suggestions on how to effectively manage my slider, I would greatly appreciate it. Thank you!

Answer №1

Take a look at the updated fiddle below,

Interactive Fiddle

If you modify the value of scopeProps to anything less than or equal to half of totalSliderItem, you will observe a difference in the outcome.

To remove the scrollbar annoyance, apply this CSS rule:

overflow: hidden;

to the element with the class slider_metacontainer.

Here's an explanation of the code:

state={        
    totalSliderItem:0, // number of items in the slider
    unitWidth:0, // width of one unit in pixels
    currentPosition:0, // current position
    updatedTotal:0// total number of elements after adding remaining elements
  } 

The above code snippet is quite self-explanatory.

let remainder = sliderContainerLength % scopeProps 
if(remainder != 0) updatedTotal += (scopeProps - remainder)
for (let i = 0; i < remainder; i++) {
  $(sliderContainer).append('<div className="slider_item"></div>'); 
}

This section handles the addition of remaining elements in case scopeProps does not evenly divide totalSliderItem. Note that jQuery library needs to be included for this functionality to work.

handleSlideMove=(direction)=>{
    let cP;
    if(direction === 'left'){
      cP = this.state.currentPosition + scopeProps;
      if(cP == this.state.updatedTotal){
        this.state.currentPosition = 0;
        document.body.style.setProperty('--item-left', 0 + "px");
      }else{
        this.state.currentPosition = cP;
        document.body.style.setProperty('--item-left', -cP*this.state.unitWidth + "px"); 
      }
    }else{
      cP = this.state.currentPosition - scopeProps;
      if(this.state.currentPosition == 0){
        this.state.currentPosition = this.state.updatedTotal - scopeProps;
        document.body.style.setProperty('--item-left', -this.state.currentPosition*this.state.unitWidth + "px");
      }else{
        this.state.currentPosition = cP;
        document.body.style.setProperty('--item-left', -cP*this.state.unitWidth + "px"); 
      }
    }
  }

For left movement, add scopeProps to the currentPosition. If this sum equals updatedTotal, reset currentPosition to 0 and move the slider back to its initial leftmost position.

Alternatively, multiply the sum by the unitWidth, update currentPosition, and shift the slider content to the right.

Similarly, for right movement, subtract scopeProps from currentPosition. If currentPosition becomes 0, set it to updatedTotal - scopeProps and move the slider all the way to the right.

Otherwise, multiply the difference by unitWidth, update currentPosition, and navigate to the left group accordingly.

Feel free to explore the full code on the Fiddle link provided.

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

Is installing Npm outside the designated client directory leading to data corruption?

I'm facing an issue in my full stack environment using node.js/react. In my project, I have a client folder named 'client' which has its own node modules file. Whenever I need to install a package, I navigate into the client folder and run n ...

Invoking function through click event binding

Check out this fiddle I have: http://jsfiddle.net/jj258ykp/2/ On BTN2 and BTN3, I get an alert when I click, but not on BTN1. I want to see the alert on BTN1 as well. Take a look at the coffeescript code snippet below: class A method: -> ...

Translating from JavaScript to Objective-C using JSON

Can someone help me figure out how to correctly 'return' this JSON object in JavaScript? function getJSONData() { var points = '{\"points\": ['; var params = polyline.getLatLngs(); ...

What steps can I take to ensure that my server is accessible to all users?

After successfully creating a chat server using Node.JS and hosting it on my LocalHost (127.0.0.1), I realized that only I have access to the chat. To make the chat server accessible to everyone, I want to deploy it on my real server. The real server URLs ...

What is the best way to connect my Angular 2 project to the "$wakanda" service in order to access and retrieve data efficiently?

Recently, I started a new project on the wakanda.io platform using angular2 and backend technologies. After creating some database entities, I now need to retrieve data from the database on the client side. To do this, I am looking for a way to import the ...

Increasing a PHP variable after executing a JavaScript function

Imagine a scenario where we have a database containing numerous items, each with an unsigned integer id (1, 2, ...). Picture a webpage that displays all these items and allows users to add new items temporarily using JavaScript only, without affecting the ...

Tips for handling alternate lines with two distinct styles in the Ace editor

I am looking to develop a unique note-taking editor using Ace. For instance, if I paste some Spanish text into the editor, I would like to add English words as notes for corresponding Spanish words. My goal is to display these English words above the resp ...

Issues with Tailwind functionality within a monorepo setup

I have set up a monorepo architecture using yarn workspaces, with Tailwind CSS being at the root of the project. I have integrated Tailwind utilities into the styles of one of the workspaces that uses React. While Tailwind is functioning properly in the pr ...

Using jQuery, you can disable an option upon selection and also change its border color

learn HTML code <select name="register-month" id="register-month"> <option value="00">Month</option> <option value="01">January</option> <option value="02">February</option> <option value="03"& ...

Accessing an Array from a service method in Angular and passing it to my main component

Within my api-service.ts, I have an array that holds some data. public getData():Observable<any[]> { return Observable.toString[ObsResult]; } Now, in the main component, I am attempting to call the getData() method to render the data in ...

The Nextjs Image was preloaded using link preload, but it remained unused after a short period following the window's load event

I've encountered an issue while working with Next.js, a React-based framework. I am attempting to display the logo.png image using the Image component provided by Next.js. My image is stored in this folder: public/img Here is the code I'm using ...

React only allows for a single active button

I have a set of buttons and I want one of them to be in an active state, while the others should not. The styling should only be applied to the active button. I have managed to change the styling when clicking on each button, but I'm struggling with d ...

How to sort objects by keys in AngularJS

Currently, I am working on building a sorting list using AngularJS. The goal is to have the data updated in the DOM dynamically when a user clicks on the name of a value. I am attempting to order the values by categories such as Bracelets, Charms, Earrings ...

Issues with managing multiple user sessions in express-session

I've been struggling with an issue for a few days now and haven't been able to find a solution. I've scoured forums and documentation, but nothing seems to work. I have a website built in Node.js, using express-session and passport for sessi ...

The function is not able to fetch the value from the Amazon S3 file, however, it is printed

Despite troubleshooting methods such as declaring the variable outside the function and attempting to return it from the function, the below code is still not returning the Amazon S3 content. It seems to work when logging the data value on the console. ...

The size of the dropdown adjusts according to the changes in the page size

Can anyone help me with an issue I'm facing in my form? Whenever I zoom in or out on my browser, the select element within the form gets resized and changes its position. Any suggestions would be greatly appreciated. Below is the code snippet for refe ...

Troubleshooting problem with Graphql API pagination

I am attempting to retrieve all repositories from a specific user. If the user has numerous repositories, pagination would be optimal. Upon observation, it seems that we can provide first and last properties. However, how can I fetch repositories between ...

Incorporating the Acts_as_votable gem alongside Angularjs for interactive voting functionality

I'm trying to figure out how to implement Acts_as_Votable in an Angular template for a car voting system. Despite my efforts, I can't seem to display the vote count when rendering the list in Angular. I think I may need to establish some kind of ...

InitAuth0 Auth0 encountering deepPartial error in Next.js with TypeScript setup

Having some trouble setting up auth0 with nextjs using typescript. When I try to initialize Auth0, I encounter an error regarding deep partials, Argument of type '{ clientId: string; clientSecret: string; scope: string; domain: string; redirectUri: st ...

The file name is not visible after choosing a file

I have a customized input file type field in this component. After uploading a file, I want it to display the uploaded file name instead of "Choose File". Currently, even after uploading a file, it still shows "Choose File". import React, { Component } ...