Skip to content

Instantly share code, notes, and snippets.

@jackabox
Last active December 20, 2022 15:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jackabox/020e80915a20fcc0a8395de80aa9ca5c to your computer and use it in GitHub Desktop.
Save jackabox/020e80915a20fcc0a8395de80aa9ca5c to your computer and use it in GitHub Desktop.
Alpine Js + Header/Nav basic template with motion safe animation in.
<header
x-data="header()"
class="fixed top-0 left-0 right-0 bg-black z-30"
@scroll.window="hasScrolled = window.scrollY > 260"
>
<!-- Logo to go here -->
<!-- Navigation El -->
<nav
style="display: none"
x-show="showNav"
x-on:click.away="activeSubNav = false"
x-on:resize.window="resizeEvent"
x-transition:enter="motion-safe:transition-all ease-in-sharp motion-safe:duration-300"
x-transition:enter-start="opacity-0 transform -translate-x-full"
x-transition:enter-end="opacity-100 transform translate-x-0"
x-transition:leave="motion-safe:transition ease-in-sharp motion-safe:duration-300"
x-transition:leave-start="opacity-100 transform translate-x-0"
x-transition:leave-end="opacity-0 transform -translate-x-full"
class=""
>
<ul>
<li>
<a
href=""
:class="activeSubNav == 1 ? '' : ''"
x-on:click.prevent="activeSubNav = (activeSubNav == 1) ? null : 1"
>
<span>Menu Item</span>
</a>
<div
class=""
x-show="activeSubNav == 1"
x-transition:enter="motion-safe:transition-all ease-out duration-200"
x-transition:enter-start="opacity-0"
x-transition:enter-end="opacity-100"
style="display: none;"
>
<!-- Sub menu items -->
</div>
</li>
<!-- Repeat as needed -->
</ul>
</nav>
<header>
export default () => ({
showNav: false,
activeSubNav: null,
hasScrolled: false,
init() {
this.resizeEvent()
this.showNav = window.innerWidth > 1024
this.hasScrolled = window.scrollY > 120
},
toggleNav() {
this.showNav = !this.showNav
this.overflowClass()
},
resizeEvent() {
this.showNav = window.innerWidth > 1024
this.overflowClass()
},
overflowClass() {
const html = document.querySelector('html')
const body = document.querySelector('body')
if (this.showNav && window.innerWidth <= 1024) {
html.classList.add('overflow-hidden')
body.classList.add('overflow-hidden')
} else {
html.classList.remove('overflow-hidden')
body.classList.remove('overflow-hidden')
}
},
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment