Home > Blockchain >  Hide and Open a container when clicked on the same element
Hide and Open a container when clicked on the same element

Time:08-24

I am trying to toggle/display a pop-up when I click on an element and also hide the pop-up when the same element is clicked on or when I click on anything outside of the element.

const cartOpener = document.getElementById('cartOpener');
function toggleCart() {
    const cartContainer = document.getElementById('cartContainer');
    cartContainer.style.display = "block"    
};

Sorry, I can't add the HTML code because I'm using Tailwind CSS so Stackoverflow isn't allowing me

CodePudding user response:

This one should be the easiest way to toggle visibility with the function (just create a separate class .hidden in CSS with visibility: hidden or display: none)

add the code inside the function instead of cartContainer.style.display = "block"

if (cartContainer.classList.contains('hidden') {
  cartContainer.classList.remove('hidden')
} else {
cartContainer.classList.add('hidden) 
}

CodePudding user response:

You should create a control variable like

var clicked = 0;
document.getElementById("click").addEventListener("click", function(){
  if(clicked == 0){
  clicked = 1;
  document.getElementById("click").style.display = "none";
  return clicked
  }
  if(clicked == 1){
  clicked = 0;
  document.getElementById("click").style.display = "block";
  return clicked
  }
})
<div id="click">click me</div>

But, if you use display it will be deleted. You can use visibilty or you can give click function to another element.

  • Related