From aba1f874826f4629edace0cc640a289c3fb859a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fe=CC=81lix=20Pe=CC=81ault?= Date: Wed, 26 Feb 2020 16:00:49 +0100 Subject: [PATCH] Toggle layout button: Create a reusable function to animate pill --- src/atoms/ToggleLayout.svelte | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/atoms/ToggleLayout.svelte b/src/atoms/ToggleLayout.svelte index c85e7e8..154915b 100644 --- a/src/atoms/ToggleLayout.svelte +++ b/src/atoms/ToggleLayout.svelte @@ -19,11 +19,15 @@ const grid = document.querySelector('.photos') const toggle = document.querySelector('.toggle') const pill = toggle.querySelector('.pill') - const activeButton = document.querySelector(`.toggle [data-layout="${layoutSetting}"]`) + + // Change active pill + const toggleAnimate = (elem, pill, toggle) => { + pill.style.width = Math.round(elem.getBoundingClientRect().width) + 'px' + pill.style.left = Math.round(elem.getBoundingClientRect().left - toggle.getBoundingClientRect().left) + 'px' + } // Init of first option - pill.style.width = activeButton.getBoundingClientRect().width + 'px' - pill.style.left = activeButton.getBoundingClientRect().left - toggle.getBoundingClientRect().left + 'px' + toggleAnimate(document.querySelector(`.toggle [data-layout="${layoutSetting}"]`), pill, toggle) // Toggle layout toggleLayout = event => { @@ -44,8 +48,7 @@ } // Animate the active pill - pill.style.width = clicked.getBoundingClientRect().width + 'px' - pill.style.left = clicked.getBoundingClientRect().left - toggle.getBoundingClientRect().left + 'px' + toggleAnimate(clicked, pill, toggle) // Add/Remove active classes document.querySelectorAll('.toggle button').forEach(button => button.classList.remove('active'))