What steps can I take to improve the functionality of the slide navigation feature

I am currently working on implementing a sliding menu feature. The menu can slide open smoothly, however, I am encountering an issue when trying to close it by clicking on the 'x' button.

let openNav = document.querySelector(".slideOpen");
    let closeNav =  document.querySelector(".slideClose");
    document.addEventListener("click", () => {
        openNav.style.width = "250px";
    });
    document.addEventListener("click", () => {
        closeNav.style.width = "0";
    });
.slideOpen { height: 100%; width: 0; position: fixed; z-index: 1;     top: 0; left: 0; background-color: #111; overflow-x: hidden;   transition: 0.5s; padding-top: 60px; }

.slideOpen a { padding: 8px 8px 8px 32px; text-decoration: none; font-size: 25px; color: #818181; display: block; transition: 0.3s; }

.slideOpen a:hover { color: #f1f1f1; }

.slideOpen .slideClose { position: absolute; top: 0; right: 25px;  font-size: 36px;  margin-left: 50px; } 
<div style="font-size:30px;cursor:pointer">&#9776; open</div> 
<div class="slideOpen"> <ul>
    <li> <a href="#" class="slideClose">&times;</a> </li>
    <li> <a href="#">About</a> </li>
    <li> <a href="#">Services</a> </li>
    <li> <a href="#">Clients</a> </li>
    <li> <a href="#">Contact</a> </li>
  </ul> </div>

Answer №1

It is better to attach actionListeners to buttons (links) instead of the entire document.

let slide = document.querySelector(".slide");
let slideOpen = document.querySelector(".slideOpen");
let slideClose =  document.querySelector(".slideClose");
    slideOpen.addEventListener('click', function(event) {
        slide.style.width = "250px";
    });
    slideClose.addEventListener("click", () => {
        slide.style.width = "0";
    });
.slide { height: 100%; width: 0; position: fixed; z-index: 1;     top: 0; left: 0; background-color: #111; overflow-x: hidden;   transition: 0.5s; padding-top: 60px; }

.slide a { padding: 8px 8px 8px 32px; text-decoration: none; font-size: 25px; color: #818181; display: block; transition: 0.3s; }

.slide a:hover { color: #f1f1f1; }

.slide .slideClose { position: absolute; top: 0; right: 25px;  font-size: 36px;  margin-left: 50px; } 
<div style="font-size:30px;cursor:pointer" class="slideOpen">&#9776; open</div> 
<div class="slide"> <ul>
    <li> <a href="#" class="slideClose">&times;</a> </li>
    <li> <a href="#">About</a> </li>
    <li> <a href="#">Services</a> </li>
    <li> <a href="#">Clients</a> </li>
    <li> <a href="#">Contact</a> </li>
  </ul> </div>

Answer №2

Instead of attaching the addEventListener to the whole document, it is recommended to attach it to specific elements (open and close) only.

Here are the suggested changes:

Add a new class called openMenu to the open menu element like this:

<div style="font-size:30px;cursor:pointer" class="openMenu">&#9776; open</div>

Next, create a new variable to store the element:

let open = document.querySelector(".openMenu");

Then, update the document.addEventListener with references to open and closeNav respectively:

open.addEventListener("click", () => {
    openNav.style.width = "250px";
});
closeNav.addEventListener("click", () => {
    openNav.style.width = "0";
});

The revised code snippet will look something like this:

    let openNav = document.querySelector(".slideOpen");
    let open = document.querySelector(".openMenu");
    let closeNav =  document.querySelector(".slideClose");
    open.addEventListener("click", () => {
        openNav.style.width = "250px";
    });
    closeNav.addEventListener("click", () => {
        openNav.style.width = "0";
    });
.slideOpen { height: 100%; width: 0; position: fixed; z-index: 1;     top: 0; left: 0; background-color: #111; overflow-x: hidden;   transition: 0.5s; padding-top: 60px; }

.slideOpen a { padding: 8px 8px 8px 32px; text-decoration: none; font-size: 25px; color: #818181; display: block; transition: 0.3s; }

.slideOpen a:hover { color: #f1f1f1; }

.slideOpen .slideClose { position: absolute; top: 0; right: 25px;  font-size: 36px;  margin-left: 50px; } 
<div style="font-size:30px;cursor:pointer" class="openMenu">&#9776; open</div> 
<div class="slideOpen"> <ul>
    <li> <a href="#" class="slideClose">&times;</a> </li>
    <li> <a href="#">About</a> </li>
    <li> <a href="#">Services</a> </li>
    <li> <a href="#">Clients</a> </li>
    <li> <a href="#">Contact</a> </li>
  </ul> </div>

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

Chrome browser alignment problems

Here are the lines in my code: <TD id=“avail_1” style=“display:none;availability:hidden”>UrgentAvail</TD> <TD id=“avail1_1” style=“display:none;availability:hidden”>substitutedBy</TD> When I test the application o ...

Rearrange the position of the default app name on the navigation bar

I have developed a MVC5 application and by default, the nav-bar displays the "application name", "home", "contact", etc. The application name is positioned on the left side of the screen, but I would like to move it to the center. How can I achieve that? ...

What is the best way to include a header in my fixed navigation bar?

I'm currently facing an issue that I can't seem to resolve, and I suspect it might have something to do with the positioning. Despite my attempts to find a solution online, I still can't determine why this problem persists. My objective is ...

The CSS style is missing from the print preview

I've designed a style specifically for printing like this: #content .inner h2 { background: Red; border-bottom: solid 1px #dfdfdf; color: #000000; font-size: 20px; padding-left: 10px; } However, the red color doesn't show up in the print previe ...

How to retrieve the object's property with the highest numerical value using JavaScript

My current object is structured as follows: const obj = { happy: 0.6, neutral: 0.1, said: 0.3 } I'm trying to determine the best method to retrieve the property with the highest value (in this case, it would be "happy"). Any suggestions o ...

Eliminate a specific array from the firebase database

If I click on the delete button for item2, I want it to be removed from the list. { "items" : { "category1" : { "item" : { "0" : { "name" : "item1", }, "1" : { "name ...

Troubleshooting multiple file upload errors in Asp.net Mvc using ajax

I am attempting to implement multiple file upload in MVC using jQuery ajax but I am encountering some issues. https://i.sstatic.net/34kXO.png Here is my HTML design and code: <div id="fileinputdiv"> <input type="file" name="mainfile" id="main ...

The event resizing feature in fullCalendar2.6* seems to be experiencing some issues

After updating from fullCalendar 1.6 to 2.6, all functionality seems to be working except for eventResize. In the newer version, I am unable to see the resize arrow when attempting to adjust events, although it was functioning properly in the previous ver ...

Encountering "net::ERR_EMPTY_RESPONSE" error when making a HTTP PUT request using the HUE API in JavaScript

GET requests are functioning properly. PUT requests made from the API Debug tool are also working correctly. However, both PUT and POST requests, regardless of the data or API URL used, are resulting in the following error: example: OPTIONS net::ERR_ ...

Storing POST data in MongoDB using Node.js

I'm a beginner with node.js and I'm looking to save data from an HTML form (such as username, password, email, etc.) into MongoDB. Here is the code snippet that I am using: var Schema = new mongoose.Schema({ _id : String, name: St ...

Utilizing the dynamic flair with React's map functionality

In my display area, which is a div element, I have rendered some text using spans. I utilized the map function to render the text from an array. The issue arises when I apply a color class to the span elements within the map function, causing all text to ...

What is preventing me from invoking the function that I built using the Function() constructor?

Utilizing the Function Constructor within a function to generate functions during its call. Below is the constructor: funcGenerator(f) { return new Function( "value", "try{ return " + f + '; } catch (e) { ret ...

Deleting images from Firestore using a Vue.js componentReady to learn how to remove images

I recently came across a Vue.js image uploader component that I am trying to repurpose (https://codesandbox.io/s/219m6n7z3j). This component allows users to upload images to Firebase storage and save the downloadURL to firestore for continuous rendering of ...

Extracting CSS from a cell in a Datatable and applying it to other cells within the table

I am currently utilizing the datatables plugin in my project. One of the columns in my table is named "CSS" and it contains CSS code for styling the columns in that row. For example, the table structure in the database looks like this: Name Priority ...

`A dynamically captivating banner featuring animated visuals created with JQuery`

I am currently in the process of designing a banner for the top of my webpage, but I have yet to come across any code that meets all my requirements. To provide clarification, I have attached an illustration showcasing what I am aiming to achieve. 1) The ...

Struggling with the development of a crossfading image gallery using jQuery's .animate() function while ensuring compatibility with IE8

Seeking assistance in creating a crossfading image gallery using jQuery and the .animate() function. I'm struggling to solve the issue of smooth fadeIn for the next image while maintaining compatibility with IE8. https://jsfiddle.net/Vimpil/fqhc1e9m/ ...

When trying to make a POST request, the browser displayed an error message stating "net::ERR_CONNECTION

Currently, my project involves coding with React.js on the client side and Express.js on the server side. I have encountered an issue when attempting to use the POST method to transmit data from the client to the server for storage in a JSON file. The erro ...

Encountering a TypeError stating that the "option is undefined" error has occurred

Unexpectedly, my dropdown menu that was functioning perfectly fine is now throwing an error. I've made several changes and none of them seem to resolve the issue. Could it be a data type mismatch or am I missing something crucial here? Your insights ...

What is the best way to keep the calendar of a Datepicker always visible while still being able to select a date easily?

When I write my code, the calendar only appears when I press the TextBox. I attempted to place the datepicker in a <div>, but then I was unable to retrieve the selected date. @model Plotting.Models.CalendarModel @using (Html.BeginForm("Calendar", "H ...

Graphic background integrated into form input

Is it advisable to create colored shapes in Illustrator, export them as SVG files, and then embed input tags or textareas within these shapes to allow users to enter text? Are there alternative methods we could use for this functionality? https://i.sstat ...