Home > Software engineering >  Css visibility hidden
Css visibility hidden

Time:11-13

I'm trying to create a toggle button through javascript without a button ID and the css element visibility hidden, I have been trying to google it but can't find any good answers, I can only found how you toggle by using style.display but that doesn't work when I use visibility hidden in css. The button name for the toggle button is button2 and the hidden button has Hbutton as the ID.

document.querySelector(button8).addEventListener(click, function () {
  document.querySelector("hiddenbutton").style.visibility = "visible";
});

CodePudding user response:

Get the current style, and use a conditional.

document.querySelector(button8).addEventListener(click, function() {
  const button = document.querySelector("hiddenbutton");
  let current = getComputedStyle(button).getPropertyValue("visibility");

  button.style.visibility = current == "visible" ? "hidden" : "visible";
})

CodePudding user response:

You can use the computed style to determine whether or not the element is visible.

document.querySelector("button").addEventListener("click", function(){
  let p = document.querySelector("p");
  let visibility = getComputedStyle(p).visibility;
  if(visibility == "hidden")
    p.style.visibility = "visible";
  else
    p.style.visibility = "hidden";
});
p
{
  visibility: hidden;
}
<p>I will disappear</p>
<button>Toggle</button>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You can actually do this by toggling through classes which is more simple! Just create a class e.g. .hide and set the visibility to hidden. Whenever you click on the button, the selected button's class will be toggled through the given class(.hide).

document.querySelector('.toggle').addEventListener('click', () => {
  document.querySelector('.myBtn').classList.toggle('hide');
});
.hide {
  visibility: hidden;
}
<button class="myBtn">You See Me!</button>
<button class="toggle">toggle</button>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

It is very simple:

document.querySelector(button8).addEventListener(click, function () {
  var element = document.querySelector("hiddenbutton")
  if (element.style.visibility == "visible") {
    element.style.visibility = "hidden"
  } else {
    element.style.visibility = "visible"
  }
});
  • Related