Home > Software engineering >  How can I change the CSS display property when clicking on a link/button?
How can I change the CSS display property when clicking on a link/button?

Time:02-02

I have a ul with the id of "menu-list". I have set the display property to "none" in my CSS file, but I would like it to change to "flex" when clicking on a link.

I am using the click event on the link to trigger the change of the display property, but nothing happens when I click on it.

When logging the value of the display property to the console inside myFunction(), I just get a blank log in the console, with no value displayed.

What am I doing wrong?

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 >
  <div >
    <nav id='menu'>
      <div >
        <img src="src/assets/images/hp-logos_white.png" alt="logo" >
      </div>
      <ul id="menu-list">
        <li ><a href="">Home</a></li>
        <li ><a href="">Home</a></li>
        <li ><a href="">Home</a></li>
      </ul>
      <a href=""  onclick="myFunction()">
        <i ></i>
      </a>
    </nav>
  </div>
</div>

CodePudding user response:

Few issues here:

You use an anchor instead of a button and as such it will redirect you to a new site.

Then the answer explains why your toggle is not working. However, the modern solution is to simply toggle a CSS class:

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 >
  <div >
    <nav id='menu'>
      <div >
        <img src="src/assets/images/hp-logos_white.png" alt="logo" >
      </div>
      <ul id="menu-list">
        <li ><a href="">Home</a></li>
        <li ><a href="">Home</a></li>
        <li ><a href="">Home</a></li>
      </ul>
      <button>
        Click to toggle
      </button>
    </nav>
  </div>
</div>

CodePudding user response:

Switch the order of your comparison since initially no inline style is 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 >
  <div >
    <nav id='menu'>
      <div >
        <img src="src/assets/images/hp-logos_white.png" alt="logo" >
      </div>
      <ul id="menu-list">
        <li ><a href="">Home</a></li>
        <li ><a href="">Home</a></li>
        <li ><a href="">Home</a></li>
      </ul>
      <a  onclick="myFunction()">
        <i >Click</i>
      </a>
    </nav>
  </div>
</div>

  • Related