Skip to content

Instantly share code, notes, and snippets.

@andrevandal
Last active February 10, 2021 18:08
Show Gist options
  • Save andrevandal/7d90aa022c06644caadd4e2ccc413a11 to your computer and use it in GitHub Desktop.
Save andrevandal/7d90aa022c06644caadd4e2ccc413a11 to your computer and use it in GitHub Desktop.
<template>
<header
:class="[
'header',
{
'header--visible': showing,
'header--hidden': !showing,
},
]"
>
<TheNotificationBar />
<TheTopbar />
</header>
</template>
<script lang="ts">
import Vue from 'vue'
export default Vue.extend({
name: 'TheHeader',
data: () => ({
showing: true,
eventsToListen: ['resize', 'scroll', 'load'],
elToModify: as undefined | HTMLElement,
lastHeight: 0,
lastScrollTop: 0,
}),
mounted() {
const [elToModify] =
((document.querySelectorAll(
'section'
) as unknown) as Array<HTMLElement>) || []
this.init(elToModify, this.eventsToListen)
},
methods: {
init (elToModify: HTMLElement | undefined, eventsToListen){
// console.log(elToModify)
if (!elToModify) return;
this.elToModify = elToModify
this.eventsToListen.forEach((event) => {
// console.log(`listening ${event} event`)
document.addEventListener(`${event}`, () => {
// console.log(`${event} triggered`)
this.change(event)
})
})
this.change('load')
}
},
change(event = '') {
// console.log(event)
if (!this.eventsToListen.includes(event)) return
this.changeHeight()
// console.log(this.lastHeight)
// console.log(event === 'scroll')
if (event === 'scroll') this.changeVisibility()
},
changeVisibility() {
// Credits: "https://github.com/qeremy/so/blob/master/so.dom.js#L426"
const st = window.pageYOffset || document.documentElement.scrollTop
// console.log(st, this.lastHeight, this.lastScrollTop)
if (st < this.lastHeight) return
this.showing = st < this.lastScrollTop
// console.log(this.showing ? 'up' : 'down')
this.lastScrollTop = st <= 0 ? 0 : st // For Mobile or negative scrolling
},
changeHeight() {
const heigth = this.$el.clientHeight
// console.log(this.lastHeight === heigth, !heigth, !this.elToModify)
if (this.lastHeight === heigth || !heigth || !this.elToModify) return
// console.log(this.elToModify)
this.elToModify.style.minHeight = `calc(100vh - ${heigth}px)`
this.lastHeight = heigth
},
},
})
</script>
<style lang="postcss">
.header {
@apply sticky z-10 top-0 min-h-full transform transition-transform ease-in-out duration-300;
&--visible {
@apply translate-y-0;
}
&--hidden {
@apply -translate-y-28;
}
}
</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment