Skip to content

Commit 7d086b1

Browse files
committed
auto position controls
1 parent d97d67c commit 7d086b1

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

src/Elastic.Documentation.Site/Assets/image-carousel.ts

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ class ImageCarousel {
3333

3434
this.initializeSlides()
3535
this.setupEventListeners()
36+
this.positionControls()
3637
}
3738

3839
private initializeSlides(): void {
@@ -132,6 +133,64 @@ class ImageCarousel {
132133
(window.innerWidth || document.documentElement.clientWidth)
133134
)
134135
}
136+
137+
private positionControls(): void {
138+
if (!this.prevButton || !this.nextButton) return
139+
140+
// Wait for images to load before positioning
141+
const images = Array.from(this.container.querySelectorAll('img'))
142+
if (images.length === 0) return
143+
144+
let loadedCount = 0
145+
const totalImages = images.length
146+
147+
const positionAfterLoad = () => {
148+
loadedCount++
149+
if (loadedCount === totalImages) {
150+
this.calculateControlPosition()
151+
}
152+
}
153+
154+
images.forEach(img => {
155+
if (img.complete) {
156+
positionAfterLoad()
157+
} else {
158+
img.addEventListener('load', positionAfterLoad)
159+
img.addEventListener('error', positionAfterLoad) // Handle failed loads
160+
}
161+
})
162+
}
163+
164+
private calculateControlPosition(): void {
165+
if (!this.prevButton || !this.nextButton) return
166+
167+
const images = Array.from(this.container.querySelectorAll('img'))
168+
let minHeight = Infinity
169+
170+
// Find the smallest image height among all images
171+
images.forEach(img => {
172+
const height = img.offsetHeight
173+
if (height > 0 && height < minHeight) {
174+
minHeight = height
175+
}
176+
})
177+
178+
// Position controls at 40% the height of the smallest image
179+
// But ensure a minimum distance from the top (50px) and don't go below 80% of the smallest image
180+
if (minHeight !== Infinity && minHeight > 0) {
181+
const fortyPercentHeight = Math.floor(minHeight * 0.4)
182+
const minTop = 50 // Minimum 50px from top
183+
const maxTop = Math.floor(minHeight * 0.8) // Maximum 80% down the smallest image
184+
185+
const controlTop = Math.max(minTop, Math.min(fortyPercentHeight, maxTop))
186+
187+
this.prevButton.style.top = `${controlTop}px`
188+
this.nextButton.style.top = `${controlTop}px`
189+
190+
// Debug logging (remove in production)
191+
console.log(`Carousel controls positioned: minHeight=${minHeight}px, controlTop=${controlTop}px`)
192+
}
193+
}
135194
}
136195

137196
// Export function to initialize carousels

0 commit comments

Comments
 (0)