Switch back and forth between `display: none` and `display: flex` using JavaScript

There is a JavaScript function in place for a responsive navigation system that includes a burger button to toggle the visibility of the navigation menu when the screen size is too small.

The issue I am facing is that despite setting the CSS style as display:none, the navigation links are displayed upon loading the page. However, after initial load, the burger button functions correctly and allows toggling between display: none and display: flex. What could be causing this behavior where display: none is ignored on load?

function myBurger() {
  var x = document.getElementById("navLinks");
  if (x.style.display === "none") {
    x.style.display = "flex";
  } else {
    x.style.display = "none";
  }
}
.navigation1 {
  width: 100%;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: space-between;
  padding: 3rem 3rem;
  .logo img {
    height: 5rem;
  }
  i {
    display: none;
  }
  .navLinks {
    display: flex;
    a {
      padding-left: 2rem;
      align-self: center;
      color: $secondaryColor;
    }
  }
}


@media (max-width: 700px) {
  #icon {
    align-self: center;
    i {
      font-size: 3rem;
      display: block;
    }
  }
  .navLinks {
    flex-direction: column;
    width: 100%;
    padding-top: 2rem;
    padding-bottom: 2rem;
    display: none;
    .nav-link {
      padding-left: 0;
    }
  }
}
<div class="navigation1">
  <div class="logo">
    <img src="logo.svg" alt="logo">
  </div>
  <a href="javascript:void(0);" id="icon" onclick="myBurger()">
    <i class="fa fa-bars"></i>
  </a>
  <div class="navLinks" id="navLinks">
    <a class="nav-link active" href="#">Home</a>
    <a class="nav-link" href="#">Portfolio</a>
    <a class="nav-link" href="#">Services</a>
    <a class="nav-link" href="#">About</a>
    <a class="nav-link" href="#">Contact</a>
  </div>
</div>

Thank you

Answer №1

The statement x.style.display == 'none' will not function as expected because the HTMLElement.style property only retrieves properties from the inline style="" attribute, and not the actual or computed style.

To achieve the desired result, you should use getComputedStyle(), which provides the actual style rules applied to that specific element.

function myBurger() {
    const el = document.getElementById('navLinks');
    if (window.getComputedStyle(el).display === "none") {
        el.style.display = "flex";
    } else {
        el.style.display = ""; // Removes flex so it defaults back to `none` as specified in the CSS.
    }
}

In this scenario, JavaScript is not necessary - you can simply utilize a hidden <label> with a

<input type="checkbox" />
along with the :checked ~ selector trick:

#menuTrigger { display: none; }

#menuTrigger:not(:checked) ~ #navLinks {
    display: none;
}

#menuTrigger:checked ~ #navLinks {
    display: flex;
}
<div class="navigation1">

    <div class="logo">
        <img src="logo.svg" alt="logo">
    </div>

    <input type="checkbox" id="menuTrigger" />
    <label for="menuTrigger">
        <i class="fa fa-bars">Click me</i>
    </label>

    <div class="navLinks" id="navLinks">
        <!--links, no need to be put in a list -->
        <a class="nav-link active" href="#">Home</a>
        <a class="nav-link" href="#">Portfolio</a>
        <a class="nav-link" href="#">Services</a>
        <a class="nav-link" href="#">About</a>
        <a class="nav-link" href="#">Contact</a>
    </div>
  
</div>

Answer №2

The issue at hand lies in the specificity of the CSS selector. It is important to incorporate the necessary selector within the media query for optimal results:

@media (max-width: 700px) {  
    // ... 
    .navigation1 .navLinks {
        display: none;
        // ...
    }
}

Instead of:

@media (max-width: 700px) {  
    // ... 
    .navLinks {
        display: none;
        // ...
    }
}

To enhance specificity, consider using the following structure:

.navigation1 {
  // ...
  .navLinks {
    display: flex;
    // ...
  }
}

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

In order to determine if components linked from anchor elements are visible on the screen in Next.js, a thorough examination of the components

Currently, I am in the process of developing my own single-page website using Next.js and Typescript. The site consists of two sections: one (component 1) displaying my name and three anchor elements with a 'sticky' setting for easy navigation, a ...

Comparison of single-line and multi-line CSS styles placement

There seems to be a debate among CSS developers regarding the preference for multi-line or single-line formatting. Some argue that multi-line is favored for its ease in finding specific properties within the CSS file. However, others believe that single- ...

Database not receiving input data from AngularJS form submission

Having some trouble saving form data to the database using angularjs. Not sure what I'm doing wrong. Here's my HTML form: <form id="challenge_form" class="row" > <input type="text" placeholder="Challenge Name" ng-model="ch ...

Why is Ajax/FormData rounding my decimal values?

When sending data from a form to my PHP script, I am utilizing the new FormData() method to retrieve the values. However, there are additional values that I append later on which are not part of the form: var fd = new FormData(document.getElementById(&apo ...

Conceal and reveal content using jQuery

I'm struggling with creating a functionality to hide and show content when a user clicks on a button (checkbox). I've written some code but it's not working as expected. The issue is that the content doesn't hide when the checkbox is cl ...

Designing a login window that appears as a popup and blurs out the background page for enhanced security

I am in the process of developing a login/register page and I would like to implement a feature where, upon clicking the 'register now' button on the home page, a popup appears within the same website with a transparent and dull background. An ex ...

Submitting requests in Node.js Express

Can a request for a specific route be dropped using Node.js and express? For example, not returning an HTTP status or any headers, but simply closing the connection? app.get('/drop', function(req, res) { //What is the method to drop the requ ...

Recommendations for Configuring VPS for Angular2 and .Net Application

My team and I are currently in the process of developing an application that combines Angular2 for the front-end and Web API ASP.NET for the back-end. We are currently at the stage of configuring a VPS for this application but unfortunately, we lack the ...

Harnessing the Power of JSON Data Extraction with JavaScript

I stored the data in JSON format using the setItem method: localStorage.setItem('orderproduct', JSON.stringify([{imageSource: productImg, productTitle: title, productQuantity: qty, productPrice: finalprice}])); When I inspect it, this is how it ...

Child div set to 100% height within parent div with auto height

After scouring the internet for hours in search of an answer, I found myself reading articles like Floats 101 on alistapart and browsing through countless similar questions on stackoverflow. I have reached a point where I feel like I must ask my question b ...

The discrepancy in the array leads to a result of either 1 or an undetermined

Array x = [3,5,7,9,1] Array y = [3,7,8] z = x - y this should result in z = [5,9,1] (7 is common but I want it excluded) Below is the code snippet: function arrayDifference(x, y) { var arr = []; var difference = []; for (var i = 0; i<x.length& ...

The issue with Open Sans and sans-serif fonts not rendering properly in all web browsers

I am having trouble with websites that use the Open Sans font appearing with a strange handwriting style. I'm not sure where this issue is originating from. Here are some things I have tried: Using In-Private browsing Disabling all extensions Testin ...

Using .load() function in jQuery prevents .mouseenter() from functioning properly on loaded content

I'm facing an issue with a page that has a navigation bar loading content from another page into a content div when a navigation item is clicked. The loaded content includes various divs, one of which has the style display: none. This hidden div sits ...

What is the best way to utilize functions from different JavaScript files?

I'm currently handling server-side javascript and I've got confidential data that needs to remain secure, stored in a private directory. If I choose to enclose this data within a function, how can I go about invoking that function from a separate ...

Customizing the Material UI theme colors using Typescript

I have created my own unique theme and now I am attempting to assign one of the custom colors I defined to a button. However, when I try to set it as: color={theme.pallete.lightGrey} I run into this error message: No overload matches this call Overload 1 ...

Fetch response headers not being detected by Web Worker

Currently in my chrome extension, I'm utilizing web workers to collect response header cookies from a specific website. Interestingly, when I execute the request on the main thread, the response contains all the expected cookies. However, when the exa ...

Troubleshooting the issue with jQuery JSON post functionality

Hey there, I'm having some trouble with posting a variable in jQuery to my controller. It seems like the post is not working correctly because when I try to retrieve it in my controller, I get an 'undefined index' error. Here's what I c ...

Verifying the absence of values in destructured variables

In my code, I have set up three constants based on an object. const {standing_bid_amt, min_increment, starting_price} = props.auction.auction; The problem arises when the object auction is empty, resulting in the constants being undefined. To address this ...

Is it possible to send a JSON array back to a Telegram bot using Node.js?

I'm facing a challenge with my telegram bot. I've developed the bot using node js with Java as the backend. The issue arises when a user inputs a category in the bot, which should then return a list of options under different categories. The prob ...

The issue of a background image not appearing on Chrome and Firefox has been identified

I am experiencing an issue where a background image is not showing up on Chrome or Firefox, but it displays properly on other browsers. The problem occurs with relative and hard links Substituting the image file works, but the video disappears Adblock is ...