What is preventing my JavaScript if-else statement from functioning properly?

I've been experimenting with a mobile-friendly navigation menu, and I'm facing an issue where the menu opens (JS IF statement) but doesn't close (JS ELSE statement). I'm unsure why it's opening but not closing.

P.S. I'm new to JavaScript, so it could be something simple that I have overlooked. Thank you!

Here is the code snippet I am currently working on:


function myFunction(x) {
    x.classList.toggle("change");
}

function navChange() {
    var x = document.getElementById("myNav").style.height;
    if (x === "0%") {
        document.getElementById("myNav").style.height = "100%";
    } else {
        document.getElementById("myNav").style.height = "0%";
    }
}

.overlay {
    height: 0%;
    width: 100%;
    position: fixed;
    z-index: 1;
    top: 0;
    left: 0;
    background-color: rgb(0,0,0);
    background-color: rgba(0,0,0, 0.9);
    overflow-y: hidden;
    transition: 0.5s;
}

/* CSS Styles Here */

If you have any insights or suggestions, please share them. Your time and help are greatly appreciated!

Answer №1

The errors I am seeing are due to assigning values within conditions.

a = 15;
b = 10;
if(a = b) alert("hello world");

After this code runs, a is now 10 because assignment was used instead of equality testing, which should be:

if( a == b)

Furthermore, it seems like you are trying to test the style properties set through CSS and using style.height will not give you the desired result. You should specify the unit such as PX or others.

var height = window.getComputedStyle(document.getElementById("element")).height;
var height = parseInt(height, 10);
if( height > 1510 ) {
    //do something
}

Answer №2

Everything EasyBB mentioned holds true, and here's a demonstration of how it can be accomplished in a neat manner:

function toggleClass(element) {
    element.classList.toggle("change");
}

function adjustNavHeight() {
    var navHeight = document.getElementById("myNav").clientHeight; // Using clientHeight to ensure we get the actual height
    if (navHeight == 0){ 
     document.getElementById("myNav").style.height = "100%";
    } else {
     document.getElementById("myNav").style.height = "0";
    }
}
.overlay {
    height: 0%;
    width: 100%;
    position: fixed;
    z-index: 1;
    top: 0;
    left: 0;
    background-color: rgba(0,0,0, 0.9);
    overflow-y: hidden;
    transition: 0.5s;
}
/* Additional CSS code omitted for brevity */
<div id="myNav" class="overlay">
  <div class="overlay-content">
    <a href="#">About</a>
    <a href="#">Services</a>
    <a href="#">Clients</a>
    <a href="#">Contact</a>
  </div>
</div>

<div class="container" onclick="toggleClass(this), adjustNavHeight()">
  <div class="bar1"></div>
  <div class="bar2"></div>
</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

Guidelines for bringing in a personal local variation of a node package

Currently in the process of developing a javascript project that relies on a kepler.gl dependency. In order to make necessary modifications to the kepler.gl source code, I am encountering difficulties importing the updated version correctly. The current s ...

What could be causing the data in the data table to remain undeleted unless the page is manually refreshed

I am facing an issue with the delete button functionality. When I press the button, it successfully deletes the row but requires a page refresh to make the deleted row disappear. How can I resolve this problem and ensure that the row is deleted without the ...

Tips for concealing broken images in jQuery/JavaScript when generating dynamic content

Is there a way to hide the broken images in this dynamically generated HTML code using JavaScript? Unfortunately, I don't have access to the source code itself. I'm new to JQuery and could really use some assistance. Below is the snippet of the ...

Is there a way to reduce the size or simplify the data in similar JSON objects using Node.js and NPM packages?

Is it possible to serialize objects of the type "ANY_TYPE" using standard Node tools.js or NPM modules? There may be multiple objects with this property. Original Json - https://pastebin.com/NL7A8amD Serialized Json - https://pastebin.com/AScG7g1R Thank ...

Tips on invoking a function from an array in JavaScript when a button is clicked

Being new to JavaScript, I encountered a challenge where I have an array of functions: allFunctions = () => [ function1(), function2(), function3(), function4(), function5(), function6(), function7(), function8(), function9() ] My go ...

Deactivate Date Field for Editing Orders in WooCommerce

Is there a way to deactivate the Date Created textbox on the Edit Orders page of Woocommerce? I attempted to use pointer-events: none; but unfortunately, it did not have any effect. I am seeking a method to disable the Date Created field. https://i.sstat ...

How do I convert images and information stored in a BLOB object into a PDF using JS, jQuery, and jsPDF?

Converting HTML code to a BLOB object as a PDF has been successful for me. var that = this; var doc = new jsPDF('p', 'pt', 'a4'); var htmlString = '<div class="container"> <img src="bas ...

This code is only functional on JSFiddle platform

I encountered an issue with my code recently. It seems to only work properly when tested on jsfiddle, and I can't figure out why it's not functioning correctly on codepen or when run from local files. Why is this code specific to jsfiddle? When ...

Mouse movement event does not correspond to identical coordinates

I'm working on a 3D animation and trying to detect collisions with the mouse. I've attempted to make a ball follow the mouse, but it's not aligning correctly. Here's a working example in CodePen This function is borrowed from another ...

Should one consider using Eval?

I encountered a scenario where I needed to dynamically retrieve the object value from an array that contained object keys retrieved from an API. I opted for a solution that involved using the eval function. class App extends React.Component { constru ...

The require statement in Vue.js is failing to function dynamically

Having trouble dynamically requiring an image in Vue.js and it's not functioning as expected <div class="card" :style="{ background: 'url(' + require(image) + ')',}"> export default { data() { return { ...

New programmer seeking to apply a dim effect to the entire photo while also adding a highlight when the image is hovered over

I am looking to add a special effect to my photos where they appear dimmed but highlighted when hovered over. Any guidance on how to achieve this would be greatly appreciated! The image is contained within a flexbox div that also contains a clickable lin ...

Reloading the table columns in a JSP page with a click of the refresh button on every row using AJAX and JavaScript

Hey there! I have a JSP page with a table where data is displayed by iterating through a list from the action class. Each row in the table has a refresh button at row level. Here is a snippet of the JSP: <script type="text/javascript"> functi ...

Updating a component in Angular 4.3.1 from within an observable callback

My Project Journey I am currently immersing myself in learning Angular by working on a personal project: developing a game that involves routing, services, and more. One of the requirements is to hide the header on the landing page (route for '/&apos ...

Attempting to position a centrally aligned div block containing images towards the left side

I'm having an issue with aligning multiple images on my webpage. I want them to be left justified when the page is resized, while still keeping the div block centered. Currently, they are all being centered: See below: Here is the HTML and CSS code ...

"Enhance your web development with Vue.js and Vue-chart.js for beautiful linear

I'm currently struggling to implement a linear gradient background on my Vue-chart.js line chart. Despite searching high and low, the documentation and examples available are not proving to be helpful. After importing the Line component from vue-char ...

What is the reason that the CSS3 property name 'filter' is not recognized in Windows 8 applications?

I'm in the process of adapting my own codepen for a Windows 8 desktop app. Everything runs smoothly on Codepen, with the exception of some CSS adjustments from -webkit- to -ms-. However, I encountered an issue regarding this specific line in the CSS s ...

What is the reason behind using a solid color background image on this site instead of a background-color hex code?

Why opt for a solid background color image instead of using the CSS style background-color? I came across a website at that used a solid background image from . What are some advantages of choosing this approach? ...

Experience a seamless transition as the background gently fades in and out alongside the captivating text carousel

I have a concept that involves three background images transitioning in and out every 5 seconds. Additionally, I am utilizing the native bootstrap carousel feature to slide text in synchronization with the changing background images. Solving the Issue ...

csslimit overflow display only left side

I am struggling to implement a drag and drop feature resembling a shopping cart. Unfortunately, the content within the box is concealing the div I want to drag when moving out of the box. Is there a method to display only the content on the left side? Che ...