Home > Blockchain >  The button element lost its features when in my webpage
The button element lost its features when in my webpage

Time:06-22

I have a problem with my button. I put a button into the header like this:

<header>
  <h1>SOME TEXT....</h1>
  <button type='button' class='HH' id='tg'>Click me</button>
</header>

and CSS:

* {
  margin: 0;
  padding: 0;
}
html, body {
  height: 100%;
  width: 100%;
  box-sizing: border-box;
}
header {
  display: flex;
  align-items: center;
  background: #2b1c1c;
  padding: 8px;
}
.HH {
  background: red;
  width: 70px;
  position: absolute;
  right: 3px;
}

JS:

const tg = document.getElementById("tg")
const nav = document.querySelector('nav')

tg.addEventListener('click', () => {
  if (nav.style.diplay === 'none') {
    nav.style.display = 'block';
  } else {
    nav.style.display = 'none';
  }
})

but button's features disappears(Like I can't click it.) What is the problem?

CodePudding user response:

In your code you are using

const nav = document.querySelector('nav')

But in HTML (at least this one) you don't have a nav defined so the code doesn't work. So I changed the code from nav to h1 to hide this element only.

It's not the cleanest code but it gives you something to start working with it.

function toggle_visibility(id) {
   var e = document.getElementById(id);
   if(e.style.display == 'block')
      e.style.display = 'none';
   else
      e.style.display = 'block';
}
* {
  margin: 0;
  padding: 0;
}

html, body {
  height: 100%;
  width: 100%;
  box-sizing: border-box;
}

header {
  display: flex;
  align-items: center;
  background: #2b1c1c;
  padding: 8px;
}

.HH {
  background: red;
  width: 70px;
  position: absolute;
  right: 3px;
}
<header>
  <h1 id="testing">SOME TEXT....</h1>
  <button type='button' onclick="toggle_visibility('testing');" class='HH' id='tg'>Click me</button>
</header>

CodePudding user response:

Firstly you misspelled "display" as diplay in your "if" statement. Secondly, I think the "if" statement may not see "nav.style.display" as a ve value. Hence, it moves to the else to set display to "none" of which, your button element is inside your nav element. Thus, you button disappears with your nav.

<header>
  <h1>SOME TEXT....</h1>
  <button type='button' class='HH' id='tg'>Click me</button>
  <nav>
    <ul style="color: #fff;">
      <li>item1</li>
      <li>item2</li>
      <li>item3</li>
    </ul>
  </nav>
</header>

const tg = document.getElementById("tg");
const nav = document.querySelector("nav");
nav.style.display = "none";

tg.addEventListener("click", () => {
  if (nav.style.display === 'none') {
    nav.style.display = "block";
  } else {
    nav.style.display = "none";
  }
});

You may try this. And try to remove your button from inside your nav

  • Related