Home > Software design >  How to make a button toggle
How to make a button toggle

Time:10-06

I am trying to make a button that when it is clicked its able to toggle display block to display none.

I know that you can use Classlist.toggle for javascript, but I am not sure if I am targeting the classess incorrectly

let showCart = document.querySelector(".product-container");
let cart = document.querySelector(".cart");

cart.addEventListener("click", () => [
  showCart.classList.toggle(".cart-show")
]);
.cart {
  margin-left: 85rem;
}

.cart-show {
  display: block;
}

.cart a {
  filter: invert(43%) sepia(32%) saturate(310%) hue-rotate(347deg) brightness(90%) contrast(88%);
  width: 0rem;
}

span {
  position: absolute;
  margin-left: 2rem;
  margin-top: -1.3rem;
}
<li >
  <a >
    <img src="./assets/icons/cart shopping icon.svg" alt="cart icon"><span>0</span></a>
</li>

<div >
  <div >
    <h5 ></h5>
    <h5 ></h5>
    <h5 ></h5>
    <h5 ></h5>
  </div>

  <div >

  </div>
</div>

CodePudding user response:

  • Use curly braces for the event listener function body. [] is used for arrays.
  • Do not prefix the class name with . when calling toggle.
  • Make the class hide the div instead (and rename it to cart-hide).

let showCart = document.querySelector(".product-container");
let cart = document.querySelector(".cart");

cart.addEventListener("click", () => {
  showCart.classList.toggle("cart-hide");
});
.cart-hide {
  display: none;
}

.cart a {
  filter: invert(43%) sepia(32%) saturate(310%) hue-rotate(347deg) brightness(90%) contrast(88%);
  width: 0rem;
}

span {
  position: absolute;
  margin-left: 2rem;
  margin-top: -1.3rem;
}
<li >
  <a >
    <img src="./assets/icons/cart shopping icon.svg" alt="cart icon"><span>0</span></a>
</li>

<div >
  Product Container
  <div >
    <h5 ></h5>
    <h5 ></h5>
    <h5 ></h5>
    <h5 ></h5>
  </div>
  <div >
  </div>
</div>

CodePudding user response:

You have to set display:none as default for element then you can add class with display:block.

.product-container {
  display:none;
}
  • Related