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.