Tips to avoid the page from scrolling to the top when the menu is opened

Whenever a user taps the menu button on the page, a full-page menu opens. However, there is an issue - the main content page automatically scrolls to the top. Can you provide suggestions on how to prevent this from happening? I have already looked into a similar question on How to disable scrolling in the background when the mobile menu is open?, but neither position:fixed nor overflow:hidden solutions have helped.

const menuOpen = document.querySelector('.menu-open');
const menuClose = document.querySelector('.menu-close');
const body = document.querySelector('.root');

function lockScroll() {
    body.classList.add('lock');
}

function unLockScroll() {
    body.classList.remove('lock');
}

menuOpen.addEventListener('click', lockScroll);
menuClose.addEventListener('click', unLockScroll);
.lock {
  position: fixed;
  height: 100vh;
  overflow-y: hidden;
}

.menu-open {
  position: fixed;
  top: 0;
  right: 0;
  cursor: pointer;
  transition: all ease 0.6s;
  border: 0;
  background: none;
  padding: 1rem 1rem 2rem 2rem;
}

.nav-container {
  position: absolute;
  left: -100%;
  width: 100%;
  height: 100vh;
  background: #f5f5f1;
  z-index: 5;
}
<header class="header">
            <button type="button" class="menu-open"><img src="./images/menu.svg" alt=""></button>
            <div class="nav-container">
                <button type="button" class="menu-close"><img src="./images/close.svg" alt=""></button>
                <div class="menu__wrapper">
                    <div class="socials">
                        <img src="./images/logo.png" alt="" class="logo" title="">
                    </div>
                    <nav class="menu">
                        <div class="menu__item">
                            <a class="menu__item-link">menu</a>
                        </div>
                        <div class="menu__item">
                            <a class="menu__item-link">menu</a>
                        </div>
                        <div class="menu__item">
                            <a href="#males" class="menu__item-link">menu</a>
                        </div>
                        <div class="menu__item">
                            <a class="menu__item-link">menu</a>
                        </div>
                        <div class="menu__item">
                            <a class="menu__item-link">menu</a>
                        </div>
                    </nav>
                </div>
            </div>
        </header>

Unfortunately, the provided solution doesn't work for me.

Answer №1

I believe the primary body components are set as static (or maybe relative if explicitly stated), unless you modify it by overriding with a fixed position.

A more optimal approach would be to keep your navigation container positioned as absolute when "menuOpen" is active, allowing the other elements to remain in their original flow and simply overlaying the full screen on top of them.

Answer №2

Based on my experience with various web development platforms, including WordPress, utilizing event.preventDefault(); has proven effective. By using this method, you can customize the default action of a link click event, preventing the page from automatically opening at the top.

Here is an example of how it can be implemented:

const toggleMenu = document.querySelectorAll(".menu-item-has-children");

toggleMenu.forEach((item) =>
  item.addEventListener("click", (event) => {
    const submenu = event.target.parentElement.querySelector(".sub-menu");
    submenu.classList.toggle("sub-menu--open");

    event.preventDefault(); // <-- This line stops the default behavior
  })
);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Res.write inexpressively proceeding without waiting for the completion of an array of promises

snippet const processAll = async (tasks) => { let processes = []; tasks.forEach(task => { if (task === "1") processes.push(asyncProcess1); if (task === "2") processes.push(asyncProcess2); if (task === "3&q ...

What is the best way to enclose an h2 with a designated class, along with the following two elements, inside a wrapper class?

Looking to select a specific block of code to wrap with a class using the jQuery .wrapAll method. I need to target the <h2> element and the two elements that follow it. Unfortunately, the elements before and after this block are inconsistent, ruling ...

The font is displaying differently when compared to Figma

I'm currently using the font Gilroy-Bold for my project, but I'm facing inconsistencies between how it appears in Figma and my React application, even though they are both sourced from the same place. Figma: https://i.stack.imgur.com/3QvY4.png ...

jqGrid display/hide columns options dialogue box

I am looking to implement a feature that allows users to toggle columns in my jqGrid. I came across a module for this purpose, but unfortunately, it is no longer supported in jqGrid 4.x. I have searched for a replacement module without success. Are there ...

Retrieve the div element by calling a scriptlet with JavaScript

I am facing an issue with a web page that includes a scriptlet like this: <div id="flash_chart"> <%=content_data['report_text']%> </div> The variable content_data['report_text'] contains a lengthy string ...

Ways to refresh a page after clicking a button inside the modal box

As a beginner in PHP and JavaScript, I am facing an issue with refreshing the page view_create_journals.php when clicking on the change button in the modal. I have added a function to the change button but it doesn't seem to be working. I'm reall ...

Jquery Error: Unable to split object

Why am I getting an error saying "Uncaught TypeError: Object # has no method 'split'" when trying to run this page by clicking on the dropdown and triggering a change event that sends an AJAX request? <html xmlns="http://www.w3.org/1999/xhtm ...

Unlocking fashion with $refs: A step-by-step guide

After using console.log(this.$refs['block' + row + column]);, I confirmed that I can successfully access the HTML element it refers to. https://i.stack.imgur.com/7KYqB.png However, when attempting to access the element's style using variou ...

JavaScript code to generate a random color for the box shadow effect

Recently, I developed a function that generates random divs containing circles. The function randomly selects a border color for each circle, and this feature is functioning correctly. To enhance the appearance, I decided to add a box shadow to the circl ...

Centered Tailwind CSS logo design

Here is my current fiddle: https://jsfiddle.net/w5c36epd/ Upon close inspection, you may notice that the logo is not properly centered. I have experiment with various flexbox options such as: <div class="flex-shrink-0 justify-center"> ...

Is it possible to highlight only a specific color on the div background?

I'm trying to create a layout similar to this: https://i.sstatic.net/dZ1ka.png I've managed to get most of it working, but I'm struggling with the yellow rectangle that spans the background of the screen. Currently, it looks like this: https ...

Strange behavior observed in the Datepicker, possibly linked to the blur event

I'm facing a challenge with the Datepicker feature. When I blur, the calendar disappears if the Datepicker was active, but the focus remains on the input field. As a result, I am unable to trigger the Datepicker again by clicking on the input field. T ...

Is there a way to ensure that the vertical scrollbar remains visible within the viewport even when the horizontal content is overflowing?

On my webpage, I have multiple lists with separate headers at the top. The number of lists is dynamic and can overflow horizontally. When scrolling horizontally (X-scrolling), the entire page moves. However, when scrolling vertically within the lists, I wa ...

Setting line chart data for Chart.js

Can you help me troubleshoot an issue I'm facing with creating a dataset for a line chart in Chart.js? Despite having an array of objects, the dataset isn't rendering correctly and I end up with two line charts instead of one. What could be causi ...

What could be the reason for my form submission redirecting to the PHP page?

(I recently discovered that I could edit and reopen the post I had previously made. Feeling a bit confused about the process...) After submitting the form, the email is sent successfully, but then I am redirected to my php page displaying the number 0. Th ...

Using JavaScript to save a file with a data URL in Internet Explorer

Need help with file conversion on different browsers. I developed an app that converts files, and everything was working perfectly in Chrome. However, when it comes to IE (10/11/Edge), I'm facing some challenges: 1) The HTML5 download attribute does ...

Caution: Prop type validation failed due to an invalid value being passed to ForwardRef(Slider)

Currently, I'm in the process of building a Material UI range Slider with two values. It functions correctly if initialized like this: const [value, setValue] = React.useState([5,20]); const [value, setValue] = React.useState([val]); const handl ...

Including an <a> tag within a JavaScript variable to utilize in an HTML statement

I want to wrap an <a> element around a JavaScript variable containing a string. The desired output should be the 'copyright symbol' followed by the 'companyName' linked as an HTML link and then the current year's date. JavaS ...

Is there a method in CSS animations that allows for endlessly repeating successive animations in a specified sequence?

While working with CSS animations, I encountered a challenge of making two animations occur successively and repeat infinitely without merging keyframes. Is there a way to achieve this using only CSS? If not, how can I accomplish it using JavaScript? I a ...

Two Ajax Requests Simultaneously

I am currently faced with the challenge of handling two requests simultaneously. The first request involves executing a lengthy PHP script that takes 10 minutes to complete (I cannot modify it using JavaScript, so that's not an option). The second ...