Looking for assistance on how to automatically close the sidebar or pull navigation menu after clicking on a menu item

My website is designed to be responsive and includes a navigation slider that is hidden off-screen by default. The slider features a vertical push/pull bar that remains visible for users to access the menu. The entire navigation slider is fixed on the page with a scrollbar within the menu.

On smaller devices, when the menu is open, it spans 100% of the viewport width. To accommodate this, I have added a top margin to the body content of 100vh to push it off the bottom of the screen. My goal is to have the menu automatically close when a user clicks on a menu item that directs them to a specific link. I have implemented an event listener on the menu items to remove the 'active' class that controls the display of the menu when it is open. However, currently, clicking on a menu item does not close the menu.

I have tested the event listener and confirmed that it works to some extent. When I change the body to 'display: none' instead of using 'margin-top: vh', clicking on the menu item successfully closes the menu. However, this approach fails to navigate the user to the specified link. I understand that this is due to the content of the body being hidden before the link is clicked, which is why I am seeking a solution using 'margin-top' instead of 'display'.

I have researched this issue but have not found a suitable solution that addresses my specific problem. As I am new to JavaScript, I would greatly appreciate any assistance and advice on how to resolve this issue.

$(document).ready(function() {
  var mquery = window.matchMedia("(max-width:767.98)");
  $('#toggle-bar').on('click', function() {
    $('#sidebar').toggleClass('active');
  });
  if (mquery.matches) {
    $('.menu-item').on('click', function() {
      $('#sidebar').removeClass('active');
    });
  }
});
.sidebar {
  display: flex;
  width: 100%;
  position: fixed;
  max-height: 100vh;
  margin-left: calc(-100% + 25px);
  /*to keep .sidebar-toggle in the view*/
}

.sidebar.active {
  margin-left: 0;
}

.sidenav {
  overflow-y: scroll;
}

.sidebar-toggle {
  width: 25px;
}

.sidebar #navpush {
  display: none;
}

.sidebar.active #navpush {
  display: inline;
}

.sidebar.active #navpull {
  display: none;
}

.body-content {
  padding: 15px;
}

.sidebar.active~.body-content {
  margin-top: 100vh;
}
<div class="container body-wrapper">
  <aside class="sidebar" id="sidebar">
    <nav class="sidenav">
      <ul id="main-nav">
        <li><a href="#section1" class="menu-item">Section 1</a></li>
        <li><a href="#sect1nav" class="dropdown-toggle" data-toggle="collapse">Section 1</a>
          <ul id="sect1nav" class="collapse submenu">
            <li><a href="#section2a" class="menu-item">Section 2A</a></li>
            <li><a href="#section2b" class="menu-item">Section 2B</a></li>
          </ul>
        </li>
        <li><a href="#section3" class="menu-item">Section 3</a></li>
      </ul>
    </nav>
    <div class="toggle-bar" id="toggle-bar">
      <div id="nav-toggle">
        <span id="navpush">&laquo;</span>
        <span id="navpull">&raquo;</span>
      </div>
    </div>
  </aside>
  <div class="container body-content">
    <div id="section1">
      <h2>Section 1 Title</h2>
      <div>
        <!-- Content -->
      </div>
    </div>
    <div id="section2">
      <h2>Section 2 Title</h2>
      <div id="section2a">
        <h3>Section 2A Title</h3>
        <div>
          <!-- Content -->
        </div>
      </div>
      <div id="section2b">
        <h3>Section 2B Title</h3>
        <div>
          <!-- Content -->
        </div>
      </div>
    </div>
    <div id="section3">
      <h2>Section 2 Title</h2>
      <div>
        <!-- Content -->
      </div>
    </div>
  </div>
</div>

Answer №1

The issue stems from the absence of units in the media query:

Corrected code (please note the inclusion of "px" at the end):

var mquery = window.matchMedia("(max-width:767.98px)");

Before editing: Within your HTML code, there are no elements labeled as "sidebar" (#sidebar) or "toggle-bar" (#toggle-bar).

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

Is there a way to have the collapsible content automatically expanded upon loading?

I came across a tutorial on w3school (https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_collapsible_symbol), which demonstrates collapsible content hidden by default. The code snippet from the link is provided below. Can someone assist me in cha ...

Capture information from an HTML5 form and securely store it in a MySQL database

I have a simple web form that includes a "date" type input field. I want to retrieve the date entered by the user and store it in my MySQL database, which has a DATE type column. I am looking for some PHP/JS magic to facilitate the communication between t ...

What is the approach for incorporating JavaScript variables in Jade templates for writing inline CSS styles?

Struggling to inject CSS code dynamically? You're not alone. style(type='text/css') #header a#logo { background:url(constants.logo) no-repeat; } @media only screen and (-webkit-min-device-pixel-ratio: 1.5) { #header a#logo { ...

Continuously decrease a sequence of identical numbers in an array through recursion

One of the key challenges was to condense an array of numbers (with consecutive duplicates) by combining neighboring duplicates: const sumClones = (numbers) => { if (Array.isArray(numbers)) { return numbers.reduce((acc, elem, i, arr) => { if ( ...

Updates to object properties are not appearing in Vue component

I am facing an issue with a Vue component that has a single prop, which is an object. Despite changing a property in this object, it does not reflect the update in the Vue template. Below is a simplified version of the component: <template> <p ...

Contrast between utilizing a WebApp that connects to an API and one that relies on backend

Whenever I develop simple web applications, I often begin by setting up a nodeJS backend, usually creating an API server with ExpressJS. When specific routes are accessed, the server responds by dynamically rendering HTML from EJS based on the current conn ...

Choosing values from a variety of select option boxes using jQuery

I'm experiencing an issue with selecting values in a multiple select option box. Despite my efforts, I haven't been able to get all the desired items selected at once. Currently, when I run the code below, only the first option is being selected ...

Inconsistency found in Ajax DataTable data updates

Incorporating a DataTable ajax feature, I pass values to the controller. Here is a simplified version of the code: $(function() { $("#tableDiv").hide(); $("#submitDateFilters").on("click", function() { displayData(); $("#tableDiv").show(); ...

Creating distinct identifiers for table cells utilizing the map function

Is there a way to assign a unique id to each MenuItem using the map() function nested within another one? <table className={classes.table}> <thead> <tr> <td /> {sit.sit.map(sit => ( <td className={ ...

Closing md-tooltip automatically after a specified timeout period

I've set up md-chips in Angular material with the following configuration: <md-chips md-chips-disable-input ng-model="session.participants"> <!-- Chip removal button template --> <button md-chip-remove class ...

What is the procedure for attaching console.log to "l" in vue.js?

The code in main.js includes the following: window.l = function () { } try { window.l = console.log.bind(console) } catch (e) { } It functions properly in non-Vue applications. However, when trying to use it in a Vue action/method like this: l("test") ...

Selenium is unable to locate an element using Jquery

sel.add_script( sel.get_location(), "jquery.js") #I am getting u'fd6c42bcc770ca9decc4f358df3688290a4257ad' idOfResultWithSomeImage=sel.get_eval("window.jQuery('#result').find('img').filter('[alt=SeleImage]') ...

Tips on managing ASP .NET API's HttpResponseMessage for file downloads

I came across a solution on how to download a file from an asp.net API at this link: As a result, I created an API handler with the following code: public HttpResponseMessage Post([FromBody]dynamic result) { var localFilePath = graph ...

Submit field values only once the form has been confirmed to be validated

My current project involves using AJAX to submit form values, with the added requirement of implementing form validation. If any field in the form is empty, the submission should be prevented. I'm facing a challenge in figuring out how to halt the for ...

What is the reason for adding CSS styles to a JavaScript file without importing them?

/Navbar.js/ import './navbar.scss'; import {FaBars, FaSearch} from "react-icons/fa"; import { useState } from 'react'; function Navbar(){ const [hide,sethide] = useState(true); const barIcon = document.querySelectorAl ...

Include and run a series of scripts in the package.json file

Exploring Node.js for the first time, I find myself in need of adding a series of scripts to package.json and running them one by one. Is this achievable with Node.js? "scripts": { "sample": "run --spec '*spec.js'&quo ...

Adjust the color of a div's background when clicked by solely using CSS

I'm looking to change the color of a specific div when it's clicked on among three different ones. The goal is to indicate which one is active without reverting back to the original color once the mouse is released, similar to a focus effect. I&a ...

Is there a way to restrict access to my website to only be opened in the Chrome browser?

Is there a way to prevent my web application from loading when the link is opened in browsers other than Chrome? Can this be achieved using Javascript or Java? I want to restrict the usage of my web application to only Chrome. Any assistance would be appre ...

I've tried multiple stack overflow solutions, but none of them seem to be effective for my issue. What am I missing

Having encountered this common question multiple times, I stumbled upon an article discussing how to allow users to refresh their browser without facing the dreaded "Confirm Form Resubmission" pop-up. The article can be found here. Following the recommend ...

Develop an npm package that includes necessary dependencies

I am working on a distributed node.js project and I want to package the project's domain in a standalone file. To start, I created a package named "common" which contains some utilities by using the following command: npm pack This created the commo ...