Fixed menu close button

Asked

Viewed 24 times

0

Hello

I was trying to make a button open and close a fixed menu with javascript but I don’t know what I’m doing wrong with my code that doesn’t work the way it should.

In theory, when the width of the div is greater than or equal to 75px, the button onClick The function of close-up if it did not have the function of open.

Code:

/* menu fixo */

var open = document.getElementById("menu-fixo").style.width;

function toggle() {
  if (open >= "75px") {
    document.getElementById("botao-abrir-menu-fixo").onclick = closeNav();
  } else {
    document.getElementById("botao-abrir-menu-fixo").onclick = openNav();
  }
}

function openNav() {
  document.getElementById("menu-fixo").style.width = "75px";
  document.getElementById("botao-abrir-menu-fixo").style.right = "75px";
}

function closeNav() {
  document.getElementById("menu-fixo").style.width = "0";
  document.getElementById("botao-abrir-menu-fixo").style.right = "0";
}
#menu-fixo {
  position: fixed;
  top: 50%;
  right: 0;
  transform: translateY(-50%);
  width: 75px;
  min-width: 0;
  min-height: 150px;
  background-color: blue;
  z-index: 100;
  transition: width 2s;
}

#botao-abrir-menu-fixo {
  position: fixed;
  top: 50%;
  right: 75px;
  transform: translateY(-50%);
  min-width: 75px;
  min-height: 75px;
  background-color: blue;
  z-index: 100;
  display: block;
  transition: right 2s;
}
<div id="menu-geral">
  <div id="menu-fixo">menu</div>
  <div id="botao-abrir-menu-fixo" onclick="toggle()">abrir</div>
</div>

1 answer

1


You are trying to get the size through the style property of the element, only that this property does not exist. To do so width should be in the element within a width property and right inline in the elements, thus:

<div id="menu-geral">
  <div id="menu-fixo" style="width: 75px;" >menu</div>
  <div id="botao-abrir-menu-fixo" style="right: 75px;" onclick="toggle()">abrir</div>
</div>

other observations:

If the button already receives the onclick="toggle()" you can simply call the function within the toggle thus:

function toggle() {
  if (open >= "75px") {
    closeNav();
  } else {
    openNav();
  }
}

you must pick up the DOM button every time you click the button, if you do not do this the variable will only be in the initial state, and will not be updated when it changes status.

function toggle() {

  var open = document.getElementById("menu-fixo").style.width;

  if (open >= "75px") {
    closeNav();
  } else {
    openNav();
  }
}

Finally I suggest you consider an approach by adding and removing classes ( and always remember which styles through Id have more priorities than by classes. https://medium.com/emanuelg-blog/understanding-a-preced%C3%Aancia-de-estilo-em-css-specificity-Heran%C3%A7a-e-cascade-effect-a437c4929173 )

  • Worked thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.