JavaScript Responsive header menu
How to create a responsive header menu with JavaScript
Watch the full tutorial here:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="./app.js" defer></script>
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<header>
<a href="#">LOGO</a>
<button id="openMenuEl" onclick="openMenuFunc()">open menu</button>
<nav id="menu">
<button id="closeMenuEl" onclick="closeMenuFunc()">close menu</button>
<a href="#service">service</a>
<a href="#about">about</a>
<a href="#product">product</a>
<a href="#contact">contact</a>
</nav>
</header>
</body>
</html>
css
* {
padding: 0;
margin: 0;
box-sizing: border-box;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
color: #141414;
}
header {
width: 100%;
height: 50px;
display: flex;
justify-content: space-between;
align-items: center;
padding: 0 15px;
border-bottom: solid 1px #f5f5f5;
position: relative;
& #openMenuEl {
display: none;
}
& #menu {
display: flex;
flex-direction: row;
gap: 15px;
& #closeMenuEl {
display: none;
}
}
}
@media only screen and (max-width: 600px) {
header {
& #openMenuEl {
display: unset;
}
& #menu {
width: 180px;
height: 100vh;
display: none;
flex-direction: column;
position: absolute;
top: 0;
right: 0;
background-color: #f5f5f5;
& #closeMenuEl {
display: unset;
}
}
}
}
javascript
const menuEl = document.getElementById('menu');
window.addEventListener('resize', () => {
if (innerWidth > '600') {
menuEl.style.display = "flex";
} else {
menuEl.style.display = "none";
}
});
function openMenuFunc() {
menuEl.style.display = "flex";
}
function closeMenuFunc() {
menuEl.style.display = "none";
}