Last active
July 4, 2021 14:02
-
-
Save lazarohcm/d5de6fe418a88cc560fb8d17800d92f0 to your computer and use it in GitHub Desktop.
100 lines gallery Vue component made, that uses IntersectionObserver and plain css snap animation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<div class="snap-gallery"> | |
<div class="carousel" ref="carousel"> | |
<div>x</div> | |
<div>y</div> | |
<div>z</div> | |
</div> | |
<div class="indicators" v-if="elements"> | |
<div | |
class="indicator" | |
:class="{ active: index == currentIndex }" | |
v-for="(item, index) of elements" | |
:key="index" | |
></div> | |
</div> | |
</div> | |
</template> | |
<script> | |
export default { | |
data() { | |
return { | |
currentIndex: 0, | |
carousel: null, | |
elements: null | |
} | |
}, | |
methods: { | |
initObserver() { | |
const observer = new IntersectionObserver( | |
(entries) => { | |
var activated = entries.reduce((max, entry) => { | |
return entry.intersectionRatio > max.intersectionRatio ? entry : max | |
}) | |
if (activated.intersectionRatio > 0) { | |
this.currentIndex = this.elements.findIndex((el) => { | |
return el == activated.target | |
}) | |
} | |
}, | |
{ | |
root: this.$refs.carousel, | |
threshold: 0.5 | |
} | |
) | |
for (let element of this.elements) { | |
observer.observe(element) | |
} | |
} | |
}, | |
mounted() { | |
this.carousel = this.$refs.carousel | |
this.elements = [...this.carousel.childNodes] | |
setTimeout(() => { | |
this.initObserver() | |
}, 1000) | |
} | |
} | |
</script> | |
<style lang="scss"> | |
.snap-gallery { | |
display: flex; | |
flex-direction: column; | |
justify-content: center; | |
align-items: center; | |
.carousel { | |
scroll-snap-type: x mandatory; | |
-webkit-overflow-scrolling: touch; | |
width: 100%; | |
white-space: nowrap; | |
overflow-x: scroll; | |
scroll-behavior: smooth; | |
> * { | |
display: inline-block; | |
scroll-snap-align: start; | |
width: 100%; | |
height: 200px; | |
background-color: lightcyan; | |
&:nth-child(odd) { | |
background-color: lightcoral; | |
} | |
} | |
} | |
.indicators { | |
margin-top: 16px; | |
display: flex; | |
.indicator { | |
width: 40px; | |
height: 4px; | |
background-color: #F7F7F7; | |
transition: background-color 200ms ease-in-out; | |
&.active { | |
background-color: #508590; | |
} | |
} | |
} | |
} | |
</style> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment