A hamburger menu, implemented as a web component.
npm i -S @substrate-system/hamburger
This is a web component. Just import the JS and CSS, then you can use the tag in your HTML.
- see code in ./example
- See a live demonstration
With a bundler such as vite,
// just import, then we can use the tag in HTML
import '@sustrate-system/hamburger'
import '@sustrate-system/hamburger/style.css'
// import the application CSS, because we are defining some CSS variables
import './index.css'
You can use the files in this module directly by linking in your HTML.
First, copy the files to a location accessible to your web server. This package includes minified files.
cp ./node_modules/@sustrate-system/hamburger/dist/index.min.js ./public/hamburger.js
cp ./node_modules/@sustrate-system/hamburger/dist/style.min.css ./public/hamburger.css
Then link to them in HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- the style -->
<link rel="stylesheet" href="/hamburger.css">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Example</title>
</head>
<body>
<!-- use the element -->
<hamburger-menu transition=800>
<a href="#example">example link</a>
<a href="#example">example two</a>
</hamburger-menu>
<!-- the JS -->
<script type="module" src="/hamburger.js"></script>
</body>
</html>
Two custom events, open
and close
.
const burger = document.querySelector('hamburger-menu')
burger?.addEventListener('open', ev => {
debug('open')
})
burger?.addEventListener('close', ev => {
debug('close')
})
Take an attribute transition
to set the time, in milliseconds that it takes
for the menu to transition in and out of the viewport.
Default is 200ms.
This corresponds to a CSS variable, --hamburger-transition
, which is the
transition time as a CSS property. Eg, in CSS,
hamburger-menu {
--hamburger-transition: .8s
}
corresponds with this HTML:
<hamburger-menu transition=800>
<a href="#example">example link</a>
<a href="#example">example two</a>
</hamburger-menu>
Note
800 milliseconds is 0.8 seconds.
Define several CSS variables to customize the appearance.
:root {
--hamburger-bgc: var(--white); /* hamburger background color */
--hamburger-color: var(--purple); /* hamburger text color */
--hamburger-hover-color: var(--bright-white); /* hover state text color */
--menu-bgc: var(--white); /* background color for the expanded menu */
--menu-color: var(--purple); /* text color for expanded menu */
--menu-hover-bgc: var(--purple); /* hover background color inside menu */
--menu-hover-color: var(--white); /* hover text color inside menu */
--menu-width: 200px;
--hamburger-transition: .2s; /* default is .2s */
}
Based on this codepen page.