Skip to content

Commit f87aedc

Browse files
committed
simplify calculation of translateX
1 parent f8f03b9 commit f87aedc

File tree

1 file changed

+9
-21
lines changed

1 file changed

+9
-21
lines changed

src/block/carousel/frontend-carousel.js

Lines changed: 9 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -121,26 +121,14 @@ class _StackableCarousel {
121121
}
122122
step++
123123
} else if ( step === 2 ) {
124-
const numSlides = this.slideEls.length
124+
// Calculate the difference between the first slide and the first clone
125+
// This is used to calculate the translateX values for the slides and clones
126+
const slideOffsetLeft = this.slideEls[ 0 ].offsetLeft
127+
const cloneOffsetLeft = this.clones[ 0 ].offsetLeft
125128

126-
// Calculate and assign the translateX values for each slide and its corresponding clone.
127-
// This ensures that when slides are swapped for infinite scrolling, they appear in the correct position.
128-
// The translateX value is based on the width of the slides and the number of slides, including margins and gaps.
129-
this.slideEls.forEach( ( slide, index ) => {
130-
const computedStyles = window.getComputedStyle( slide )
131-
const margins = parseInt( computedStyles.getPropertyValue( 'margin-left' ) ) + parseInt( computedStyles.getPropertyValue( 'margin-right' ) )
132-
const width = slide.getBoundingClientRect().width + margins
133-
134-
slide.slideTranslateX = `calc((${ width }px * ${ numSlides }) + (var(--gap) * ${ numSlides }))`
135-
136-
if ( index < this.slidesToShow ) {
137-
this.clones[ index ].slideTranslateX = slide.slideTranslateX
138-
}
139-
140-
if ( index === this.slideEls.length - 1 ) {
141-
this.clones[ this.clones.length - 1 ].slideTranslateX = `calc((${ width }px * -${ numSlides }) + (var(--gap) * -${ numSlides }))`
142-
}
143-
} )
129+
const diff = Math.abs( slideOffsetLeft - cloneOffsetLeft )
130+
this.slideTranslateX = ( this.isRTL ? -diff : diff ) + 'px'
131+
this.cloneTranslateX = ( this.isRTL ? diff : -diff ) + 'px'
144132

145133
step++
146134
} else if ( step === 3 ) {
@@ -336,10 +324,10 @@ class _StackableCarousel {
336324
const runSteps = () => {
337325
if ( step === 0 ) {
338326
this.slideEls.slice( startIndex, endIndex ).forEach( slide => {
339-
slide.style.transform = `TranslateX(${ useSlideTranslateX ? slide.slideTranslateX : 0 })`
327+
slide.style.transform = `translateX(${ useSlideTranslateX ? this.slideTranslateX : 0 })`
340328
} )
341329
this.clones.slice( startIndex, endIndex ).forEach( clone => {
342-
clone.style.transform = `TranslateX(${ useSlideTranslateX ? clone.slideTranslateX : 0 })`
330+
clone.style.transform = `translateX(${ useSlideTranslateX ? this.cloneTranslateX : 0 })`
343331
} )
344332
step++
345333
requestAnimationFrame( runSteps )

0 commit comments

Comments
 (0)