Code clean,

This commit is contained in:
2020-04-06 12:21:47 +02:00
parent 60fdf02112
commit 8fabe68241
7 changed files with 55 additions and 60 deletions

View File

@@ -3,60 +3,61 @@
// Variables
let toggleEl
let toggleLayout
let grid
let pill
let layoutSetting
// Elements
const layoutGridClass = 'photos--grid'
const layoutListClass = 'photos--list'
// 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 - toggleEl.getBoundingClientRect().left) + 'px'
}
// Toggle layout
const toggleLayout = event => {
const clicked = event.currentTarget
const type = clicked.dataset.layout
// Change the layout
switch (type) {
case 'grid':
grid.classList.add(layoutGridClass)
grid.classList.remove(layoutListClass)
break
case 'list':
grid.classList.add(layoutListClass)
grid.classList.remove(layoutGridClass)
break
default: break
}
// Animate the active pill
toggleAnimate(clicked, pill, toggleEl)
// Add/Remove active classes
toggleEl.querySelectorAll('button').forEach(button => button.classList.remove('active'))
clicked.classList.add('active')
// Remember this setting
localStorage.setItem('photosLayout', type)
}
/*
** Run code when mounted
*/
onMount(() => {
grid = document.querySelector('.photos')
// Get layout setting from storage
layoutSetting = (localStorage.getItem('photosLayout')) ? localStorage.getItem('photosLayout') : 'list'
// Variables
const layoutGridClass = 'photos--grid'
const layoutListClass = 'photos--list'
const grid = document.querySelector('.photos')
const pill = toggleEl.querySelector('.pill')
// 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 - toggleEl.getBoundingClientRect().left) + 'px'
}
// Init of first option
toggleAnimate(toggleEl.querySelector(`[data-layout="${layoutSetting}"]`), pill, toggleEl)
// Toggle layout
toggleLayout = event => {
const clicked = event.currentTarget
const type = clicked.dataset.layout
// Change the layout
switch (type) {
case 'grid':
grid.classList.add(layoutGridClass)
grid.classList.remove(layoutListClass)
break
case 'list':
grid.classList.add(layoutListClass)
grid.classList.remove(layoutGridClass)
break
default: break
}
// Animate the active pill
toggleAnimate(clicked, pill, toggleEl)
// Add/Remove active classes
toggleEl.querySelectorAll('button').forEach(button => button.classList.remove('active'))
clicked.classList.add('active')
// Remember this setting
localStorage.setItem('photosLayout', type)
}
})
</script>
@@ -84,5 +85,5 @@
<span>Grid</span>
</button>
<div class="pill" aria-hidden="true" role="presentation"></div>
<div class="pill" aria-hidden="true" role="presentation" bind:this={pill}></div>
</div>