Learning Smart
Learning Smart

Reputation: 125

How to make a button toggle

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 class="nav-item cart">
  <a class="nav-link">
    <img src="./assets/icons/cart shopping icon.svg" alt="cart icon"><span>0</span></a>
</li>

<div class="product-container">
  <div class="product-header">
    <h5 class="product-title"></h5>
    <h5 class="price"></h5>
    <h5 class="quantity"></h5>
    <h5 class="total"></h5>
  </div>

  <div class="products">

  </div>
</div>

Upvotes: 1

Views: 285

Answers (2)

Lukas249
Lukas249

Reputation: 2471

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

.product-container {
  display:none;
}

Upvotes: 0

Unmitigated
Unmitigated

Reputation: 89234

  • 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 class="nav-item cart">
  <a class="nav-link">
    <img src="./assets/icons/cart shopping icon.svg" alt="cart icon"><span>0</span></a>
</li>

<div class="product-container">
  Product Container
  <div class="product-header">
    <h5 class="product-title"></h5>
    <h5 class="price"></h5>
    <h5 class="quantity"></h5>
    <h5 class="total"></h5>
  </div>
  <div class="products">
  </div>
</div>

Upvotes: 2

Related Questions