From c665b65e032cbee55f37b8f91a8b6fa5f2df9767 Mon Sep 17 00:00:00 2001 From: Fabien egg O'Carroll Date: Mon, 13 Dec 2021 14:51:00 +0200 Subject: [PATCH] Added initial CSS&JS for Before/After card refs https://github.com/TryGhost/Team/issues/1249 This contains the initial frontend code to provide a working slider for the Before/After card. The JS is enclosed in an IIFE so as to not leak any variables, and the CSS is all scoped to the card only to avoid interfering with existing styles. --- core/frontend/src/cards/css/before-after.css | 16 ++++++++ core/frontend/src/cards/js/before-after.js | 41 ++++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 core/frontend/src/cards/css/before-after.css create mode 100644 core/frontend/src/cards/js/before-after.js diff --git a/core/frontend/src/cards/css/before-after.css b/core/frontend/src/cards/css/before-after.css new file mode 100644 index 0000000000..f3b22fd2f2 --- /dev/null +++ b/core/frontend/src/cards/css/before-after.css @@ -0,0 +1,16 @@ +.kg-before-after-card > div { + position: relative; + margin: 0 auto; +} + +.kg-before-after-card-image-before { + position: absolute; + overflow: hidden; + top: 0; + left: 0; +} + +.kg-before-after-card img { + max-width: none; + width: unset; +} diff --git a/core/frontend/src/cards/js/before-after.js b/core/frontend/src/cards/js/before-after.js new file mode 100644 index 0000000000..e038fc8a94 --- /dev/null +++ b/core/frontend/src/cards/js/before-after.js @@ -0,0 +1,41 @@ +(function () { + const beforeAfterCards = [...document.querySelectorAll('.kg-before-after-card')]; + + for (let card of beforeAfterCards) { + const isFullWidth = card.classList.contains('kg-width-full'); + const input = card.querySelector('input'); + const overlay = card.querySelector('.kg-before-after-card-image-before'); + const orientation = card.querySelector('div').getAttribute('data-orientation'); + const images = [...card.querySelectorAll('img')]; + const smallestImageWidth = Math.min( + ...images.map(img => parseInt(img.getAttribute('width'))) + ); + + function updateSlider() { + if (orientation === 'vertical') { + overlay.setAttribute('style', `height: ${input.value}%`); + } else { + overlay.setAttribute('style', `width: ${input.value}%`); + } + } + + function updateDimensions() { + const containerWidth = parseInt(getComputedStyle(card).getPropertyValue('width')); + const width = isFullWidth ? containerWidth : Math.min(smallestImageWidth, containerWidth); + for (let image of images) { + image.setAttribute('style', `width: ${width.toString()}px;`); + } + } + + input.addEventListener('input', function () { + updateSlider(); + }); + + window.addEventListener('resize', function () { + updateDimensions(); + }); + + updateDimensions(); + updateSlider(); + } +})();