Issue
I've spend lot of time trying to lock the scroll when a hamburger menu is open. Is there a solution?
My code:
<!-- Navigation bar -->
<header class="header">
<!-- Logo -->
<a href="teste.html" class="logo"><img src="img/ss.png"></a>
<!-- Hamburger icon -->
<input class="side-menu" type="checkbox" id="side-menu" />
<label class="hamb" for="side-menu"><span class="hamb-line"></span></label>
<!-- Menu -->
<nav class="nav">
<ul class="menu" id="menu">
<li class="nav-link"><a href="teste.html" class="nav-link">Home</a></li>
<li><a href="about.html">About</a></li>
<li><a href="servicos.html">Services</a></li>
<li><a href="contato.html">Contact</a></li>
<li>
<input type="button" name="nome" value="FREE ESTIMATE">
</li>
</ul>
</nav>
Solution
To lock the scroll when the menu is open, you can use JavaScript to add a class to the body element when the menu is open and remove it when the menu is closed. Here's an example of how you can achieve this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Your Page Title</title>
<style>
/* Your existing CSS styles */
body.menu-open {
overflow: hidden;
}
</style>
</head>
<body>
<!-- Navigation bar -->
<header class="header">
<!-- Logo -->
<a href="teste.html" class="logo"><img src="img/ss.png"></a>
<!-- Hamburger icon -->
<input class="side-menu" type="checkbox" id="side-menu" />
<label class="hamb" for="side-menu"><span class="hamb-line"></span></label>
<!-- Menu -->
<nav class="nav">
<ul class="menu" id="menu">
<li class="nav-link"><a href="teste.html" class="nav-link">Home</a></li>
<li><a href="about.html">About</a></li>
<li><a href="servicos.html">Services</a></li>
<li><a href="contato.html">Contact</a></li>
<li>
<input type="button" name="nome" value="FREE ESTIMATE">
</li>
</ul>
</nav>
</header>
<!-- Your page content goes here -->
<script>
// JavaScript to toggle the 'menu-open' class on the body element
document.addEventListener('DOMContentLoaded', function () {
var sideMenu = document.getElementById('side-menu');
var body = document.body;
sideMenu.addEventListener('change', function () {
if (sideMenu.checked) {
body.classList.add('menu-open');
} else {
body.classList.remove('menu-open');
}
});
});
</script>
</body>
</html>
In this example, I added a new style in the section to hide the overflow when the body has the class menu-open. The JavaScript code uses an event listener to add or remove the class based on the state of the side menu checkbox. This way, the body's overflow will be hidden when the menu is open and restored when it's closed.
Answered By - Hamza Saai
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.