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

Pagination determined by the selections made in cascading dropdown menus

Does anyone know of a tutorial on implementing pagination that is specifically tailored to dependent drop lists? I've managed to display associated records based on a selection from a dropdown list with items like {Beavers, Cubs, Scouts, Venturers, Ro ...

I am on a quest to locate the xpath for a day that is divided by the HTML line break element,

In my HTML structure, I have the following code snippet: <td class="FormLabel" valign="top"> <span class="DataLabel">Consists of:</span> </td> <td class="FormData"> <span class="BodyText"> Sunday<br> M ...

What are the most effective ways to manage state in form components using React?

As I delve into the realm of best practices for managing state in React components, I find myself grappling with different approaches. Initially, I crafted a form by creating a TextField component structured like this: var TextField = React.createClass({ ...

Employing Visual Composer within WordPress has resulted in the raw JavaScript not being properly applied to my raw HTML code

Sharing some code that functions properly in my browser and I want to implement on my WordPress page: <!doctype html> <html lang="en"> <head> <meta charset="UTF-8> <!-- Getting jQuery --> <script src="http://ajax.goog ...

Ensuring a div remains perfectly centered

Currently, I am new to HTML and still in the process of learning. I am facing a challenge in centering a button within a div, and I have been using margins to position it. While this method works well when the window is fullscreen, the button's positi ...

Having trouble getting data to send to node.js server using $.ajax post

Trying to convert a table date into an array and send it to the server side using Ajax post for the first time. Despite following all the suggestions in previous posts, I am still struggling. Utilizing body-parser to extract data on the server side. Any he ...

Unable to display Apexcharts bar chart in Vue.js application

Struggling to incorporate Apexcharts into my Vue.js site, but unfortunately, the chart isn't appearing as expected. -For more guidance on Apexcharts, check out their documentation Here HTML <div class="section sec2"> <div id="chart" ...

Problem with jQuery's UI autocomplete functionality

Implementing jQ UI Autocomplete with multiple values Below is how my function is structured: mailto_input.bind( "keydown", function( event ) { if ( event.keyCode === $.ui.keyCode.TAB && $( this ).data( "autocomplete" ).menu.active ) { ...

Incorporate an external website into HTML5 code

I have a dilemma with embedding one website into another. I am currently utilizing embed code for this purpose. <object data="http://mywebsite.com" width="100%" height="100%"> <embed src="http://mywebsite.com" width="100%" height="100%"> ...

Exporting and importing modules in Angular 1 using Webpack 2

Seeking clarification on why the current implementation is not working as expected. It seems like a simple oversight, especially since it works fine without Webpack. I prefer to stick with the current implementation, where each component/controller/etc is ...

Can the getState() method be utilized within a reducer function?

I have encountered an issue with my reducers. The login reducer is functioning properly, but when I added a logout reducer, it stopped working. export const rootReducer = combineReducers({ login: loginReducer, logout: logoutReducer }); export c ...

Verify user identities using just their passwords

For my express app, I'm tasked with creating an authentication system that uses a 4-digit pin as the password. The code is set up to save and hash the pin along with other user information when adding a new user. Since this is for an in-house server h ...

What methods exist for determining the current location or city of a user without requesting permission?

Is there a way to automatically capture the user's current location on our website without explicit permission, possibly using IP address or MAC address? Has anyone successfully implemented this method in the past? ...

Activating two buttons in jquery will trigger this action

I am currently working on developing a filter button that will perform different actions based on which buttons are pressed. Pressing button1 will trigger one action, while pressing button2 will trigger another action. If button1 is pressed first, followe ...

using sass to nest multiple classes

In an attempt to utilize nested classes with Sass, I am working on a styling code that displays a button on hover. Here is the structure of my SCSS: .item{ border-bottom: 1px dotted #ccc; text-indent: 50px; height: 81%; padding: 2px; text-transf ...

The Sortable feature is functional in all browsers except for Firefox

I am currently utilizing the following example () within my asp.net application. I have successfully implemented the sortable feature in all browsers except for Firefox, where it seems to trigger the event but doesn't execute the code. $('.c ...

The URIError occurred while attempting to decode the parameter '/December%2015,%' within the express framework

After setting up a middleware using the express framework that handles a URI with a date as a parameter, I encountered a small issue. app.get("/:date",function(req,res){ var result; var myDate=req.params.date if(moment(myDate).isValid()) ...

Problems with aligning elements to both the left and right sides of the same line

Currently, I have two divs that I would like to float on the left and right sides. However, they seem to be sticking together and I can't seem to separate them.. HTML: <nav> <div id="nav_content"> <div id="home_ico ...

What could be causing this highchart plot to fail to display in both IE and Chrome?

Check out the plot in this jsfiddle: http://jsfiddle.net/essennsee/y5HCm/ The plot looks good in Firefox, but only shows the legend in IE and Chrome. If I remove the following code snippet it works fine. Is there a different way to format the labels?: ...

Organize an array of objects in JavaScript into a structure with nested children

I am facing a challenge with organizing an array of objects based on parentId and sort values. I need to create a nested array with 'children' and ensure proper sorting. Consider the following data: [{ id: 1, sort: 2, parentId: null ...