Unable to back out of side navigation

My side navigation menu is giving me some trouble. It opens up just fine when I click the button, but it won't close back up when I click it again. The button is supposed to toggle between opening and closing the side navigation.

I've looked at similar threads on this forum and tried using the code provided by others, but it's not working in my specific case.

Additionally, I'm trying to change the shape of the button from ☰ to X whenever the side navigation is extended or retracted. The button changes its shape correctly every time, so that part is working fine.

Thanks for any help you can offer!

Here is the relevant HTML:

<div class = "icon" onclick = "Change(this)">
   <div class = "bar1"></div>
   <div class = "bar2"></div>
   <div class = "bar3"></div>                
</div>


<div id = "mysideNav" class = "sideNav">
    <a href = "#"> About the bank </a>
    <a href = "#"> Mission </a>
    <a href = "#"> Vision </a>
    <a href = "#"> Why us? </a>
    <a href = "#"> Contacts </a>
</div>    

CSS:

.icon
    {
    display: inline-block;
    cursor: pointer;
    }
.bar1, .bar2, .bar3
    {
    width: 35px;
    height: 5px;
    background-color: #333;
    margin: 6px 0;
    transition: 0.4s;
    }
.change .bar1
    {
    -webkit-transform: rotate(-45deg) translate(-9px, 6px);
    transform: rotate(-45deg) translate(-9px, 6px);
    }
.change .bar2
    {
    opacity: 0;
    }
.change .bar3
    {
    -webkit-transform: rotate(45deg) translate(-8px, -8px);
    transform: rotate(45deg) translate(-8px, -8px);
    } 
.sideNav
    {
    height: 100%;
    width: 0;
    position: fixed;
    z-index: 1;
    top: auto;
    left: 0;
    background-color: #111;
    overflow-x: hidden;
    padding-top: 60px; 
    transition: 0.5s;
    }
.sideNav a
    {
    padding: 15px 32px 15px 32px;
    text-decoration: none;
    font-size: 25px;
    color: #818181;
    display: block;
    transition: 0.3s
    }
.sideNav a:hover, .offcanvas a:focus
    {
    color: #f1f1f1;
    }                                          

Javascript:

function Change(x)
{
    var mynav = document.getElementById("mysideNav");
    x.classList.toggle("change");
    if (mynav.style.width = "0px") 
    {
       mynav.style.width = "250px";
    }
   else
   {
       mynav.style.width = "0px";
   } 
}

Answer №1

Hey, you were so close!

While checking for the current width of mynav, it seems like there was a small error in your code. Instead of checking the width directly, it looks like you accidentally declared it inside the if statement. Make sure to use == or === for comparisons. For more information on the differences between these operators, check out this link.

I've made an adjustment to your javascript below:

function Change(x)                         // script for menu icon 
{
    var mynav = document.getElementById("mysideNav");
    x.classList.toggle("change");
    if (mynav.offsetWidth === 0) 
    {
       mynav.style.width = "250px";
       console.log("open");
   }
   else
   {
       mynav.style.width = "0px";
       console.log("close");
   } 
} 

In the revised code snippet, I used offsetWidth to get the width from the element rather than the style. You can learn more about this distinction here.

Additionally, I added console.log statements to each condition block. This simple addition helped me quickly identify and resolve the comparison issue.

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

The appearance of the logo varies across various web pages on the site

Isn't it strange that my logo appears pixelated only on the home page, even though I used the same HTML and CSS code for all pages? The Html: <a href="Home.html"><img id="logo" src="../CONTENT/Images/Logo/1Sr2l8а.png" alt="logo"/></ ...

Leveraging the capabilities of the Freshdesk API

Has anyone had any experience utilizing the FRESHDESK API specifically for creating tickets? The documentation states the following: Request URL: domain_URL/helpdesk/tickets.xml Request method: POST <helpdesk_ticket> <description>Disk fai ...

When using React, draggable components with input fields may lose their ability to receive focus when clicking on the input field

<Draggable axis="y" grid={[135,135]} onStop={this.handleStop} defaultPosition={{x: this.props.task.positionX, y: this.props.task.positionY,}}> <div id="edit-task-component"> <form onSubmit={this.handleSubmit} id=" ...

The connection between the layout of dropdown menus and the way data is handled in forms

I have discovered three different methods for creating dropdowns that can be used in forms: 1) Utilizing HTML with "form-dedicated" attributes such as select and option value="" 2) Implementing the Bootstrap framework with div classes like "dropdown", Butt ...

Issue with SwiperJS not completely filling the height of a div

My issue relates to using swiperJS with multiple images, as I'm struggling to make it take the full width and height of the containing div. Despite applying styling like this to my images: .swiper-slide img { width: 100%; height: 1 ...

"Creating a Miniview Panel on a Fabric Canvas: A Step-by-Step Guide

Is there a way to add a mini view panel to my Fabric Canvas like shown in this image MiniView Panel? I want a panel in the corner of my canvas that displays the entire layout. Similar to the panel on this website . ...

"Selecting the hue of an image on an input

Is it possible to easily incorporate color images into a design? I am struggling to find the property that will allow me to do so. There is a button that contains an image. .button { background: url('../image/arrow.png') 189px no-repeat ...

Do specific elements of typography adjust according to the size of the window?

I'm always amazed by the creative solutions that come out of this community. So I'm reaching out to see if anyone knows a way to achieve something unique with CSS! Specifically, I'm curious if it's possible to make certain horizontal p ...

EventListener fails to detect any changes in the dropdown menu

I am currently delving into the world of Django and JavaScript, but I am encountering an issue with the addEventListener function. It seems to be malfunctioning and I am at a loss. Can anyone provide insight into what may be causing this problem? Here is ...

The Google Books API has reached its limit for requests

Encountering a rate limit exceeded error from the Google Books API while using this demo: To reproduce, open the developer console in Chrome and perform some searches. The rate limit errors will be displayed in the console. [],"lazyUpdate":null},"status" ...

What could be causing my web application to not properly identify angular.js?

As a newcomer to angular, I have been struggling to incorporate it into my web application (VS) as I keep encountering issues with recognizing angular. Despite trying various methods, the result remains the same - angular is not being recognized. I dow ...

Delete an entry from the list

I have a fully functional Ajax call and function that fills up a datalist. This datalist is utilized to choose from a limited list and add it to a UL element on the page. Once an option is added from the datalist to the actual list, I aim to eliminate that ...

Creating a WasmModuleBuilder in V8 that enables functions to return multiple values

I'm currently working on creating a wasm function using WasmModuleBuilder from V8: var builder = new WasmModuleBuilder(); builder.addMemory(5, 5, false); builder.addFunction("func", {params: [125,125], results: [125,125]}); builder.functions[0].addBo ...

Tips for storing form data in MongoDB

I'm currently working on a form and I need help extracting text from the form in order to save it into MongoDB. Here is an excerpt from my tweets.ejs file: <form method="post" action="/tweets"> <input type="text" id="txt" name="text"/> & ...

How can an array of file paths be transformed into a tree structure?

I am looking to transform a list of file and folder paths into a tree object structure (an array of objects where the children points to the array itself): type TreeItem<T> = { title: T key: T type: 'tree' | 'blob' childr ...

Error in Formatting Labels in CSS

I currently have a form with textboxes that include validation. Everything works smoothly when clicking the save button for the first time, but if we fill out the textboxes and then remove the text, an error message is displayed on the textboxes. You can v ...

The navigation bar extends beyond the container

First time diving into bootstrap and struggling with my items overflowing the container. Here's a snippet of my code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equi ...

Issue with nav-pill not functioning properly on localhost server set up with XAMPP

<!-- Customized Navigation Pills --> <ul class="nav nav-pills" role="tablist"> <li class="nav-item"> <a class="nav-link active" data-toggle="pill" href="#home">My Home</a> </li> <li class="nav-item ...

Attempting to dynamically insert a new row into a table using jQuery, with the added condition of limiting the total number of rows to four

I'm facing an issue with a table that has no rows. I want to dynamically add rows by clicking an anchor tag, with a limit of 4 rows. When the limit is reached, I need to display an alert message saying "only 4 rows allowed." However, currently, it kee ...

Retrieving Information From a Targeted div Identifier with PHP

Possible Duplicate: read XML tag id from php How can I retrieve data from a specific div ID using PHP? I want to extract data from a div with the ID of <div id="content">, so that all the content within that div can be stored in a variable. Alt ...