Steps to hide the sidenav when clicking on a hyperlink

Everything is working smoothly with the navigation, but there's a small glitch to address: the side navigation bar should close automatically when a link is clicked on this one-page website. Can anyone assist me with this issue?

Here is the code snippet:

function openNav() {
  document.getElementById("mySidenav").style.width = "250px";
}

function closeNav() {
  document.getElementById("mySidenav").style.width = "0";
}
.sidenav {
  height: 100%;
  width: 0;
  position: fixed;
  z-index: 1;
  top: 0;
  right: 0;
  background-color: #111;
  overflow-x: hidden;
  transition: 0.5s;
  padding-top: 60px;
}
<div id="mySidenav" class="sidenav">
  <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
  <a id="nav" href="#about">About</a>
  <a id="nav" href="#service">Services</a>
  <a id="nav" href="#contact">contact</a>

</div>
<p>Click to open</p>
<span style="font-size:30px;cursor:pointer" onclick="openNav()">&#9776; open</span>

The desired behavior is for the sidenav to close automatically upon clicking a link.

Answer №1

Your code is functioning perfectly. However, it appears that you just overlooked adding the closenav() function to the onclick events on the actual links.

function openNav() {
  document.getElementById("mySidenav").style.width = "250px";
}

function closeNav() {
  document.getElementById("mySidenav").style.width = "0";
}
.sidenav {
  height: 100%;
  width: 0;
  position: fixed;
  z-index: 1;
  top: 0;
  right: 0;
  background-color: #111;
  overflow-x: hidden;
  transition: 0.5s;
  padding-top: 60px;
}
<div id="mySidenav" class="sidenav">
  <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
  <a id="nav" href="#about" onclick="closeNav()">About</a>
  <a id="nav" href="#service" onclick="closeNav()">Services</a>
  <a id="nav" href="#contact" onclick="closeNav()">contact</a>

</div>
<p>Click to open</p>
<span style="font-size:30px;cursor:pointer" onclick="openNav()">&#9776; open</span>

Answer №2

Give this a try:

HTML Code:

<div id="mySidenav" class="sidenav jsSideNav">
          <a href="javascript:void(0)" class="">&times;</a>
          <a id="nav" href="#about">About</a>
          <a id="nav" href="#service">Services</a>
          <a id="nav" href="#contact">Contact</a>
    </div>
    <p>Click to open</p>
    <span style="font-size:30px;cursor:pointer" class="jsToggleNav">&#9776; Open</span>

CSS Styles:

.sidenav {
  height: 100%;
  width: 0;
  position: fixed;
  z-index: 1;
  top: 0;
  right: 0;
  background-color: #111;
  overflow-x: hidden;
  transition: 0.5s;
  padding-top: 60px;
}
.sidenav.active {
    width: 250px;
}

JavaScript Functionality:

$(document).ready(function(){
        $(".jsToggleNav").on('click', function(){
            if($(".jsSideNav").hasClass('active')) {
                $(".jsSideNav").removeClass('active');
            } else {
                $(".jsSideNav").addClass('active');
            }
        })
    });

If you are using jQuery, make sure to follow the class naming convention for JavaScript operations.

Hope this solution proves helpful for your project.

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

Once an AJAX call is made, the state of a React component changes but fails to trigger a

In this section, users have the opportunity to comment on posts. Once the data is received and verified on the server side, I attempt to update the value of this.state.comments. However, there is an issue where the comment section in the component does not ...

Alter the button's color seamlessly while staying on the same page

I have implemented a feature that allows me to change the category of photos without having to leave the page and it works perfectly. My next goal is to create a button system where the pre-defined category of a photo is indicated by a button with a green ...

Tips for creating a sidebar table of contents with CSS

I'm looking to design a webpage with a side bar table of contents (TOC) similar to the one found here: The current placement of the TOC on the HTML page is as follows: <h2>Table of Contents</h2> <div id="text-table-of-contents&quo ...

Ways to determine whether a website is operating on http or https protocol

There is a http call being made from my AngularJS application. I'm uncertain about the protocol used by the target website. Therefore, I need to determine whether the target site uses HTTP or HTTPS. Below is a snippet of my code. var Path12 = "https: ...

Tabbable bootstrap with dropdown functionality

I am currently in the process of integrating Bootstrap tabs and dropdown menus using version 2.3.4 <div class="container"> <div class="navbar navbar-fixed-top"> <div class="navbar-inner"> <div class="container-fluid"> ...

What is the best method for integrating JavaScript into my Express.js application that is also utilizing Socket.IO?

In order to synchronize time for my countdown project, I am utilizing the timesync package. server.js const app = require('express')(); const http = require('http').Server(app); const io = require('socket.io')(http); const po ...

Potential dangers involved in sending HTML content through an AJAX request over a secure HTTPS connection

I am exploring the idea of dynamically loading HTML content, such as updating a Bootstrap modal dialog's contents using AJAX calls instead of refreshing the entire page. However, before I proceed, I want to understand the potential risks involved and ...

What is the best way to display a SolidJS component on the screen?

I am currently working on a unique menu design for my application. The concept involves rendering a functional component within an element created in the body using createRoot and render methods. https://i.stack.imgur.com/g6Ofv.png export function create ...

Laravel is sending out the HTTP header text together with the payload response

My current setup involves using React and jQuery on the frontend like this: $.ajax({ url: ... method: 'POST', contentType: 'application/json', dataType: 'json', success: (response) => { ... }, error: (err) => ...

execute a function for every regex match found within a string

When working with WordPress or PHP in general, I came across this interesting recommendation for email obfuscation, and I would like to: Convert email addresses to mailto links Encode the mailto links using str_13() Decode them client-side using JavaScri ...

The functionality of getDownloadURL is not functioning as expected with Firebase Storage on the web platform

Having some trouble with my code as it does not seem to log the download URL of the file being uploaded. I am getting this error message: GET ...{URL that is not the download URL}... 404() This is the code snippet in question. //Get image va ...

How can I pan/move the camera in Three.js using mouse movement without the need to click?

I am currently working on panning the camera around my scene using the mouse. I have successfully implemented this feature using TrackballControls by click and dragging. function init(){ camera = new THREE.PerspectiveCamera(45,window.innerWidth / windo ...

<a> slightly off-centered horizontal alignment

I've been trying to center a link using different methods like text-align:center and display:inline-block, but it seems to be slightly off-center. I've attached images along with my code below for reference. Any assistance would be greatly apprec ...

Error encountered while attempting to download PDF file (blob) using JavaScript

Recently, I have been utilizing a method to download PDF files from the server using Laravel 8 (API Sanctum) and Vue 3. In my Vue component, I have implemented a function that allows for file downloads. const onDownloadDocument = (id) => { ...

Transferring information to the server using a fetch request

Can anyone help me understand why the server is returning POST {} {} as empty objects after sending a request? I'm confused about where this data has gone. Why did it disappear? I'm completely lost on how to solve this... index.js: window.add ...

Looking for a custom textured circle in three.js?

Is there a way to create a circle with a texture on one side in three.js without using sprites? I was considering using THREE.CylinderGeometry, but I'm unsure of where to add the "materials" in the new THREE.CylinderGeometry(...) section. Any suggest ...

Connecting the mat-progress bar to a specific project ID in a mat-table

In my Job Execution screen, there is a list of Jobs along with their status displayed. I am looking to implement an Indeterminate mat-progress bar that will be visible when a Job is executing, and it should disappear once the job status changes to stop or ...

Beating the API call system: Utilizing the RxJS skip operator

Currently, I am attempting to utilize the skip operator in RxJS to skip the initial API call. However, despite my efforts, I have not been successful in achieving this. const source = of('a', 'b', 'c', 'd', 'e&a ...

Are we looking at a declaration of an arrow function? Is this concept even real?

I have been exploring the concept of function expressions versus function declarations with arrow functions. From my understanding, this is an example of an arrow function expression: const fred = greeting = () => { console.log("Hello from arrow ...

Creating a glowing shimmer using vanilla JavaScript

After successfully creating the Shimmer Loading Effect in my code, I encountered a hurdle when trying to implement it. The effect is visible during the initial render, but I struggle with utilizing it effectively. The text content from my HTML file does no ...