Guide to creating a toggle button

Can someone help me create a button that toggles between displaying block and display none when clicked?

I've been trying to use Classlist.toggle with JavaScript, but I'm not sure if I have the correct classes targeted.

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>

Answer №1

  • Remember to use curly brackets for the event listener function body; square brackets are used for arrays.
  • When calling the toggle function, do not prefix the class name with a period (.).
  • Instead of hiding the div directly, create a new class called cart-hide and apply it to hide the cart.

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>

Answer №2

To make an element invisible by default, you need to use display:none and then apply a class with display:block.

.item-box {
  display:none;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How Can I Utilize a URL Parameter Twice to Execute SQL Queries in Two asp.DataLists on a Single Page?

I've been trying everything, but I just can't seem to get one query to function properly. My goal is to retrieve information from the SQL Server database in two separate queries - one for album names (based on URL parameter) and another for song ...

Repairing the Left-sided Popup Leaflet

Can someone help me with fixing the positioning of the Popup to the left of the map? Currently, it does not stay aligned to the left edge when moving the map. I tried using position: fixed in my styling, and while everything looks good when zooming, it br ...

The slider customization on Joomla is functioning perfectly on my local machine, but it seems to be encountering some issues on

Having recently started working on a Joomla website for the first time, I encountered some challenges when trying to add a slider module. Despite successfully implementing the slider on my local machine, I faced issues when transferring the code to the liv ...

Using jQuery to load content with a dynamic variable instead of specific element IDs

I am facing a minor jQuery issue. I am trying to load a specific area of an external HTML document into a div, but instead of loading just that particular area, the entire document is being loaded. Here's the code snippet for the trigger: $('a& ...

Problem regarding the widths of HTML <table> elements

I am working with a <table> that has 3 columns structured as follows: table { border: 1px dashed goldenrod; } td { border: 1px solid gray; } <table> <tr> <td width="120">Some content</td> <td width="150"> ...

Is there a way to stop TD from going to the next line?

I am using Javascript to dynamically generate a table and I want it to extend beyond the boundaries of the page. When I manually create the table, it works fine and extends off the page, but once I put it into a loop, the <td> elements wrap onto a se ...

Modifying attributes of an object within a document using Mongoose

Encountering an issue where the sentiment object in my document is not updating. Within my Model Class, there's a field named sentiment of type Object structured like this: sentiment: { terrible: 0, bad: 0, okay: 0, good: 0, fantastic: 0 } ...

tips for using Node Mailer to send emails without using SMTP

Currently, I am facing an issue with sending emails through nodemailer. Although I have successfully used my gmail account for this purpose in the past, I now wish to switch to using my business email to communicate with clients on a regular basis. The cu ...

Ember - connecting to a JSON data source

Recently, I have been following a tutorial/example from codeschool and everything is going well. However, the example code includes the line: App.ApplicationAdapter = DS.FixtureAdapter.extend(); Now, I want to maintain all the existing functionality but ...

Ways to extract information from a table cell located next to a table cell with colspan

As a beginner in web scraping, I am gradually making progress. However, I'm facing a tough challenge with this particular task. My goal is to extract data from the ESPN NBA boxscore website: I aim to scrape the names of players labeled as "DNP" (Did ...

``There seems to be an issue with CSS Transform/Transition not functioning properly

Here is some CSS code that I used to animate a list of items on my website: selector { display: flex; } #primary li a { -webkit-background-clip: text; -webkit-text-fill-color: transparent; ...

Displaying server errors in an Angular componentIn this tutorial, we

As I work on creating a registration page, my focus has been on posting data to the server. I have successfully implemented client-side and server-side validation mechanisms. Managing client-side errors is straightforward using code such as *ngIf="(emailAd ...

Align the bottom of the Material UI icon with the bottom of the text

Below is the code snippet that I am working with: <td> <WarningAmberIcon sx={{ color: '#cc0000' }} />&nbsp;&nbsp; If you cannot print in colour, please <a href="https://www.aviva.ie/insurance/car-insurance/faqs/#do ...

Having difficulty in executing the node app.js script

I am currently learning node.js and encountering an issue when trying to run the app.js file using the command node app.js. The terminal shows no output, neither errors nor any other information. Here is the sequence of steps I have followed: $ brew insta ...

Styling Fonts in Safari with CSS

Because FixedSys doesn't appear correctly in Chrome or Safari, I switch it to Lucida Console. While this solution works for Chrome, I encounter a problem with Safari. Unless Lucida Console stands alone, the font will not display as desired. If there a ...

Leveraging keypress() for managing all Vue interactions

I am in the process of converting a game from Javascript/jQuery to Vue. This particular game is entirely controlled by keyboard input, with no mouse interaction involved. Players navigate through the game using the "up" and "down" arrow keys to cycle thro ...

Import several image files using AngularJS

I recently came across a helpful tutorial that demonstrates how to upload pictures from your local computer using AngularJS directives. As a newcomer to Angular, I followed the instructions but now I'm stuck on modifying it to display the selected ima ...

I'm having trouble getting rid of this stubborn loader on the website

I am currently utilizing the following template: . My objective is to eliminate the preloader progress bar that displays the loading progress of the page in percentage. The files associated with this preloader are as follows: Loader CSS File - www[dot]the ...

The jqGrid displays a plus sign even when the subgrid is empty while using XML

I am utilizing jqGrid to display data with a subgrid in XML format. $("#UDFs").jqGrid({ ajaxGridOptions: { contentType: 'application/xml; charset=utf-8' }, datatype: 'xmlstring', datastr: data, xmlReader: { root: "Respo ...

Error: FileReader is not defined in Node.js (Nest.js) environment

I am working on converting my image to base64 using a custom function. However, when I try to execute the code, I encounter an error message stating ReferenceError: FileReader is not defined. This error has left me puzzled and unsure of its cause. Below i ...