Javascript Programação

Asked

Viewed 42 times

-3

I have a question in javascript,

code:

function abrirNav(){
    if (document.getElementById("style-switcher").style.width="0px"{
    document.getElementById("style-switcher").style.width="200px";
}

I need that when the width of style-switcher:

  • is 0, change to 200px,
  • is in 200px change to 0.

If anyone can help me I’d be grateful.

1 answer

1

You can use the offsetWidth for this, example:

function changeSize(){
  const element = document.getElementById('myDiv');
  
  if(element.offsetWidth === 0){
    element.style.width = '200px';
  } else {
    element.style.width = '0px';
  }
}
#myDiv{
  width: 0px;
  height: 10px;
  background: red;
  
  transition: width 1s ease;
}
<div id="myDiv"></div>

<br />
<button onclick="changeSize()">Click me!</button>

The idea is that you keep a reference to the saved element in a variable, and that through it you can get the width and other properties of its element and even change them.

Browser other questions tagged

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