From cf5407fb690ca303e6fb505106ed1b0787f4bd9c Mon Sep 17 00:00:00 2001 From: Halil Nevzat Demirel Date: Thu, 5 Dec 2024 21:06:40 +0300 Subject: [PATCH] Fix Dynamic Parent Padding Calculation for Swiffy Slider This pull request introduces a dynamic solution to account for cumulative parent element paddings in Swiffy Slider. The changes ensure that the slider functions seamlessly, even when placed inside containers with various padding values. The fix dynamically calculates the cumulative padding of all parent elements and adjusts the slider's CSS variables accordingly, resolving layout and functionality issues in complex DOM structures. --- src/swiffy-slider.js | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/src/swiffy-slider.js b/src/swiffy-slider.js index 7bf194b..a4dc922 100644 --- a/src/swiffy-slider.js +++ b/src/swiffy-slider.js @@ -1,11 +1,13 @@ -const swiffyslider = function() { +const swiffyslider = function () { return { version: "1.6.0", init(rootElement = document.body) { rootElement.querySelectorAll(".swiffy-slider").forEach(sliderElement => this.initSlider(sliderElement)); }, - + initSlider(sliderElement) { + this.adjustForParentPadding(sliderElement); // Adjust for parent padding dynamically + sliderElement.querySelectorAll(".slider-nav").forEach(navElement => navElement.addEventListener("click", () => this.slide(sliderElement, navElement.classList.contains("slider-nav-next")), { passive: true }) ); @@ -23,6 +25,23 @@ const swiffyslider = function() { } }, + adjustForParentPadding(sliderElement) { + const sliderContainer = sliderElement.querySelector(".slider-container"); + if (!sliderContainer) { + return; + } + let totalPadding = 0; + let currentElement = sliderContainer.parentElement; + while (currentElement) { + const styles = getComputedStyle(currentElement); + const paddingLeft = parseFloat(styles.paddingLeft) || 0; + const paddingRight = parseFloat(styles.paddingRight) || 0; + totalPadding += paddingLeft + paddingRight; + currentElement = currentElement.parentElement; + } + sliderContainer.style.setProperty("--swiffy-slider-item-reveal", `${totalPadding}px`); + }, + setVisibleSlides(sliderElement, threshold = 0.3) { let observer = new IntersectionObserver(slides => { slides.forEach(slide => { @@ -142,4 +161,4 @@ if (!document.currentScript.hasAttribute("data-noinit")) { } } } -} \ No newline at end of file +}