Is there a way to modify the CSS display property upon clicking a link or button?

I have a ul with the id of "menu-list". The display property is set to "none" in my CSS file, but I want it to switch to "flex" when a link is clicked.

I am trying to use the click event on the link to change the display property, however, nothing happens when I click on it.

When I log the value of the display property to the console inside myFunction(), no value is displayed, just a blank log. What could be the issue?

let menuList = document.getElementById("menu-list");

function myFunction() {
  console.log(menuList.style.display);

  if (menuList.style.display === "none") {
    menuList.style.display = "flex";
  } else {
    menuList.style.display = "none";
  }
}
#menu-list {
  display: none;
}
<div class="container">
  <div class="inner">
    <nav id='menu'>
      <div class="logo">
        <img src="src/assets/images/hp-logos_white.png" alt="logo" class="fluid">
      </div>
      <ul id="menu-list">
        <li class="menu-list-item"><a href="">Home</a></li>
        <li class="menu-list-item"><a href="">Home</a></li>
        <li class="menu-list-item"><a href="">Home</a></li>
      </ul>
      <a href="" class="icon" onclick="myFunction()">
        <i class="fa fa-bars"></i>
      </a>
    </nav>
  </div>
</div>

Answer №1

There are a few issues that need to be addressed:

The code is currently using an anchor tag instead of a button, which may cause redirection to a new page.

A better solution would be to toggle a CSS class for the desired functionality:

const menuList = document.getElementById("menu-list");
const button = document.querySelector('button');

button.addEventListener('click', function() {
  menuList.classList.toggle('d-flex')
})
[id="menu-list"] {
  display: none;
}

.d-flex {
  display: flex;
}
<div class="container">
  <div class="inner">
    <nav id='menu'>
      <div class="logo">
        <img src="src/assets/images/hp-logos_white.png" alt="logo" class="fluid">
      </div>
      <ul id="menu-list">
        <li class="menu-list-item"><a href="">Home</a></li>
        <li class="menu-list-item"><a href="">Home</a></li>
        <li class="menu-list-item"><a href="">Home</a></li>
      </ul>
      <button>
        Click to toggle
      </button>
    </nav>
  </div>
</div>

Answer №2

It is suggested to change the order of your comparison as no inline style is initially set on the element.

let menuList = document.getElementById("menu-list");
function myFunction() {
  if (menuList.style.display === "flex") {
    menuList.style.display = "none";
  } else {
    menuList.style.display = "flex";
  }
}
#menu-list {
  display: none;
}
<div class="container">
  <div class="inner">
    <nav id='menu'>
      <div class="logo">
        <img src="src/assets/images/hp-logos_white.png" alt="logo" class="fluid">
      </div>
      <ul id="menu-list">
        <li class="menu-list-item"><a href="">Home</a></li>
        <li class="menu-list-item"><a href="">Home</a></li>
        <li class="menu-list-item"><a href="">Home</a></li>
      </ul>
      <a class="icon" onclick="myFunction()">
        <i class="fa fa-bars">Click</i>
      </a>
    </nav>
  </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

Issues with implementing KendoUI's datepicker in conjunction with Angular

My index.html file contains the following imports: <script src="content/js/angular.js"></script> <link href="content/js/kendo.common-material.min.css" rel="stylesheet" /> <link href="content/js/kendo.material.min.css" rel="styleshe ...

Attempting to load an image through an AJAX Request may prove to be unsuccessful

I am facing an issue with using an AJAX request to load a gif image from the following source: Despite my attempts, using the response on the image source like this: $('#cat-thumb-1').attr('src', 'data:image/gif;base64,' + d ...

Is there a way to effortlessly upload numerous files in one go when browsing with jquery or JavaScript?

Currently working on a web application and looking to enable multiple file upload functionality within a single browse session, as opposed to selecting one file at a time. The goal is for users to be able to easily select multiple files with just one clic ...

What is the proper way to use Object.entries with my specific type?

On my form, I have three fields (sku, sku_variation, name) that I want to use for creating a new product. I thought of converting the parsedData to unknown first, but it seems like a bad practice. export type TProduct = { id: string, sku: number ...

Hide the menu when a user clicks on any of its options

On a next.js website, there is a hidden panel that slides out from the edge when a button is clicked. Inside the panel, there is a menu. The panel and the menu are separate components. The goal is to have the panel open and close when the button is clicked ...

nested dropdowns in Bootstrap 4

I'm currently working on a nested dropdown menu feature. Although I have successfully implemented the functionality to display the next level, I am facing an issue where it does not close upon clicking. Check out my code here! Here is the JavaScript ...

Error: Attempting to access a property of an undefined object resulting in TypeError (reading 'passport')

I am currently working on a project that requires me to display user profiles from a database using expressjs and mongoDB. However, I have encountered an issue and would appreciate any solutions offered here. Here is the code from my server: const express ...

Terminating a client connection in Node.js using socket.io

What is the best way to terminate the socket connection on the client side? I am currently utilizing: socket.io 0.9 node.js 0.10.15 express 3.3.4 For example, when calling localhost/test -- server side var test = io .of('/test') .on(&apos ...

The C# counterpart to the JavaScript "OR assignment" concept

Is there a comparable feature in C# to JavaScript's assignment syntax var x = y || z;? This operation does not result in true/false. If y is defined, it assigns that value to x, otherwise it assigns z to x, even if it is undefined. Keep in mind, in J ...

Unveiling the Secrets of Unearthing Data from JSON

My code receives JSON strings through a JSONP call. Although I'm aware of the general JSON structure, I don't know the specific keys and values it will contain. The typical structure is as follows: [ {"key_name": "value"}, {"key_name": ...

Issue: React child components cannot be objects (received: object with keys)

Hey everyone, I could really use some help figuring out what I'm doing wrong. Here is the error message I'm receiving: Error: Objects are not valid as a React child (found: object with keys {id, title, bodyText, icon}). If you meant to render a ...

Create a single JSON object by searching through two collections in MongoDB

Is it possible for you to assist me in combining data from two collections into one JSON format? Users [ user_id, user_name, city_id ] [ { "name": "Anton", "user_id": 1, "city_id": 1 }, { "name": "Vasiliy", ...

Tips for adding a class to the output of a jQuery ajax request?

I've been searching for a solution to this issue without any luck. Below is the code I have: jQuery("#categories_parent_id").change(function() { id = jQuery("#categories_parent_id").val(); jQuery.ajax({ type: ...

What is the method for obtaining the number of weeks since the epoch? Is it possible to

Currently, I am setting up a DynamoDb store for weekly reporting. My idea is to use the week number since 1970 as a unique identifier for each report record, similar to epoch milliseconds. Here are some questions I have: How can I determine the current w ...

Replicate the functionality of a mouse scrolling event

I have incorporated Jack Moore's Wheelzoom jQuery plugin to zoom and drag an SVG image on my website. However, I also want to include manual zoom in and out buttons for the users. I am considering two options to achieve this - triggering a mouse whe ...

Step-by-step Guide on Installing VueJs Medium Editor

After spending countless hours trying to install Medium Editor in VueJs, I finally got it working on a single page vuejs. However, I hit a roadblock when trying to make it work with the webpack file structure: ├── main.js # app en ...

When a VueJS button is located within a div that also contains a link, clicking on

Can someone help me with my HTML issue? <a href="/someplace"> <div> <vuecomp></vuecomp> <span>Click row for more info</span> </div> </a> Following is the Vue component I am working on... ...

Sticky sidebar panel featuring a stationary content block

I have a sidebar that is set to position:fixed; and overflow:auto;, causing the scrolling to occur within the fixed element. When the sidebar is activated, the element remains static on the page without any movement. My goal: I am looking to keep the .su ...

The functionality in the React Native code that uploads images to an S3 bucket is currently failing to initiate the network request

I have been using a redux-observable epic to upload images to my AWS S3 bucket through react-native-aws3. It has been functioning smoothly for quite some time. However, recently it seems to have stopped entering the .map and .catch blocks of code. I suspec ...

Only display the Google map marker when it is within the current view

I'm looking to enhance the animation of my Google map marker. I've successfully customized my map, implemented a unique marker, and enabled the animation feature. However, there are a couple of obstacles preventing it from functioning as desired. ...