What could be the issue with this JavaScript if/else statement?

My goal is to have the text "open" displayed when the navigation bar is not visible, and when it is visible, the text "open" should be hidden. I am new to HTML and JavaScript, and I wrote the following code, but it is not working as expected. Can someone please help me identify what is wrong?

  
var nav = document.getElementById("Navbar");
var b = document.getElementById("Body");
var open = document.getElementById("Open");
var close = document.getElementById("Close");

function openNav() {
   nav.style.width = "250px";
   b.style.marginLeft = "250px";
   check();
}

function closeNav() {
  nav.style.width = "0px";
  b.style.marginLeft= "0px";
  check();
}

function check() {
  if (nav.style.width == "0px") {
    close.style.display = "none";
    open.style.display = "block";
  } else {
    open.style.display = "none";
    close.style.display = "block";
  }
}

Script update

  
var nav = document.getElementById("Navbar");
var b = document.getElementById("Body");
var open = document.getElementById("Open");
var close = document.getElementById("Close");

function openNav() {
   nav.style.width = "250px";
   b.style.marginLeft = "250px";
   check();
}

function closeNav() {
  nav.style.width = "0px";
  b.style.marginLeft= "0px";
  check();
}

function check() {
  if (nav.style.width == "0px") {
    close.style.display = "none";
    open.style.display = "block";
  } else {
    open.style.display = "none";
    close.style.display = "block";
  }
}

what i'm getting

Open Navbar all good here Closed Navbar not good, Open button is invisible

Answer №1

To accurately compare values, you must use double equal signs in your code.

Incorrect

if (nav.style.width = "0px")

Correct

if (nav.style.width == "0px")

Best Practice

if (nav.style.width === "0px")

Answer №2

Upon closer inspection, it appears that there are a couple of issues beyond just the comparison being == instead of =, as previously mentioned.

Firstly, the id for the close button should be:

"Close" rather than "close" in the HTML

Secondly, you are not invoking the check() function in the JavaScript after modifying any styles, which explains why the open/close functionality remains invisible after the page loads and when clicking the buttons.

The correct approach would be:

function openNav() {
   nav.style.width = "250px";
   b.style.marginLeft = "250px";
   check();
}

function closeNav() {
  nav.style.width = "0px";
  b.style.marginLeft= "0px";
  check();
}

Lastly, the check function should be:

function check()
  {
    if (nav.style.width == "0px")
      {
        close.style.display = "none";
        open.style.display = "block";
      }
    else
      {
        open.style.display = "none";
        close.style.display = "block";
      }
  }

to toggle which one is shown.

Working Snippet:

var nav = document.getElementById("Navbar");
  var b = document.getElementById("Body");
  var open = document.getElementById("Open");
  var close = document.getElementById("Close");

  function openNav() {
   nav.style.width = "250px";
   b.style.marginLeft = "250px";
   check();
}

function closeNav() {
  nav.style.width = "0px";
  b.style.marginLeft= "0px";
  check();
}
function check()
{
  if (nav.style.width == "0px")
    {
      close.style.display = "none";
      open.style.display = "block";
    }
  else
    {
      open.style.display = "none";
      close.style.display = "block";
    }
}
    ...
    (CSS code here)
    ...
<!-- HTML code here -->
    ...
    (HTML code here)
    ...

Answer №3

It is advisable to opt for the == operator within your statement as opposed to using =.

Answer №4

It's advisable not to alter the size of the specified element. Instead, opt for using nav.toggle() in JQuery to modify its visibility.

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 request method 'PUT' is not currently supported

Currently, I am working on a project that involves springboot, angularjs, and restful services. Here is my REST controller: @RequestMapping(value="/updatestructure/{ch}", method = RequestMethod.PUT) public @ResponseBody Structurenotification updateStruct ...

Learn how to use jQuery to load a text file containing arrays and then format them as

I'm attempting to load a .txt file containing multidimensional arrays using AJAX, and then sort through the data to display it on my website. However, I'm facing an issue where the data is only returning as plain text, even after trying to use JS ...

Animate the React Bootstrap modal only when it is shown or hidden

I am experimenting with the idea of transitioning smoothly from one modal to another in bootstrap Modals for react (using react-bootstrap). However, I am facing challenges due to the fade CSS class causing flickers and unwanted animations. My goal is to h ...

Encountering a 405 error when attempting to send a request through an express route in a Next

After deploying my Express js routes in Next js on hosting, I encountered an error 405 when sending requests to the route. However, everything works fine when I test it on localhost. I'm puzzled by this issue. Can anyone help me understand what' ...

Event triggered when a text input field becomes active (excluding onfocus) in the FireFox browser

I'm currently working on detecting when a text input field is active. Initially, I used the onfocus event, but I encountered an issue where the onblur event would be triggered when the window was no longer in focus, causing unintended consequences in ...

Having difficulty updating the state with editorState retrieved from the server in ReactJs when using draftJs

Incorporating a rich text editor into React using draftJs has been successful. The editorState data is converted to raw data, stringified, and sent to the server for rendering on the front end. However, I am facing challenges in updating the editorState ...

What is the most efficient way to post an array and iterate through it using PHP?

As the user types into an input field, jQuery's replace function is used to immediately create an array. The objective is to send these values to PHP for a live search on a specific MySQL table. I've managed the input field and the ajax call, bu ...

How can I prevent a block of white space from collapsing in CSS, without relying on the presence of a DIV element?

I am facing an issue with maintaining space above the Title in my design. The design includes elements like Title, Description, and Image. The challenge is to ensure that there is a 20px space above the Title, as shown in the example below: https://i.ssta ...

Troubleshooting: Bootstrap 5 Submenu Dropdown Fails to Expand

I am struggling with implementing a dropdown menu in Bootstrap 5. Although the dropdown menu is visible, I am facing an issue where the submenu items do not expand upon clicking. Below is the code snippet that I am using: <body> <nav class=&qu ...

Retrieve the values of a function using the Firebase database

Hey, I'm in a bit of a pickle trying to retrieve the values returned by my function. I can see them just fine in the console log, but how do I actually access them when calling the function? function getprofile(useruid) { return firebase.database ...

What modifications need to be made to the MEAN app before it can be deployed on the server?

Following a tutorial on Coursetro, I was able to successfully build an Angular 4 MEAN stack application. However, when it comes to deploying the app on a server running on Debian-based OS, I am facing some challenges. The application should be accessible o ...

drag items on your smartphone with ease

Hello everyone, I am looking to make items draggable on a smartphone as well. Here is my HTML code: <input class="inputText mb-2 border border-primary rounded" v-model="newTodo" @keypress.13='addTodo' placeholder="W ...

What is the best way to fill the dropdown options in every row of a data table?

This HTML snippet displays a data table with test data and corresponding dropdown options. <tr> <th> Test Data </th> <th> Test Data ...

Interactive JavaScript button that navigates me to a document without the need to click

I'm facing an issue with my small project. I've been learning javascript and managed to create a script that calculates the square of a number provided by the user. var checkIt = function(){ var theNumber = Number(prompt("Please enter a number ...

Import .vue single file component into PHP application

I've been struggling to integrate a .vue single file component into my php app without using the inline template method. Since I don't have a node main.js file to import Vue and require the components, I'm not sure how to properly register m ...

Implement Material-UI's built-in validation for form submission

I'm in the process of setting up a form with validation: import React from 'react'; import { useForm } from "react-hook-form"; import axios, {AxiosResponse} from "axios"; import {Box, Button, Container, Grid, Typography} ...

Are you struggling with Grails - Ajax submission not functioning properly?

Trying to update a div when a form is submitted, but it seems like something is missing. Here's the HTML code: <%@ page contentType="text/html;charset=UTF-8" %> <html> <head> <meta name="layout" content="main" /> ...

Accessing querySelector for elements with numerical values in their name

Here is a URL snippet that I need to work with: <h1 id="header_2" title="mytitle" data-id="header_title" class="sampleclass " xpath="1">mytitle<span aria-label="sometest" class="sa ...

Refreshing material ui select choices based on user input

Just getting started with Reactjs and I need some help. I have a material ui select element that has default values set, and when I click the 'ADD USER' button and submit, I can add new values to the select element. I'm also able to delete o ...

Using Javascript to retrieve a variable and dynamically updating the source of an HTML iframe

I have two JavaScript variables, 'long' and 'lat', in the code below. My challenge is to append these values to the end of the iframe URL. I would appreciate assistance on modifying the code below to achieve this. The iframe code bel ...