Steps for adding products to your shopping cart without using a JavaScript framework:

As a newcomer to web development, I took on the challenge of creating an e-commerce website using only HTML, CSS, and vanilla JavaScript (without any frameworks).

I've encountered a roadblock while trying to implement the "Add to Cart" functionality for my products. Below is a snippet of my code:

<div class="small-container">
    <div class="row">
        <div class="col-4">
            <img src="images/20 ps4.png" alt=""/></a>
            <h4>20 Playstation Store(PSN)</h4>
            <p>$20.00</p>
            <button type="button" class="btn1" ><h3 class="text-btn">add to cart</h3></button>
        </div>

        <div class="col-4">
            <img src="images/25 ps4.png" alt="" />
            <h4>25 Playstation Store(PSN)</h4>
            <p>$25.00</p>
            <button type="button" class="btn1" onclick="window.location.href='cart.html'"><h3 class="text-btn">add to cart</h3></button>
        </div>
    </div>

For the JavaScript part:

function ready() {
    var removeCartItemButtons = document.getElementsByClassName('btn1')
    for (var i = 0; i < removeCartItemButtons.length; i++) {
        var button = removeCartItemButtons[i]
        button.addEventListener('click', removeCartItem)
    }

    // Continue with other JavaScript functions...
}

In terms of styling with CSS:

.row {
    margin-top: 50px;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    justify-content: space-around;
}

.small-container{
    max-width: 1080px;
    margin: auto;
    padding-left: 25px;
    padding-right: 25px;
}

.col-4 {
    flex-basis: 25%;
    padding: 10px;
    min-width: 200px;
    margin-bottom: 50px;
    transition: transform 0.5s;
}
  
.col-4 img {
    width: 100%;
}

Thank you for your help!

I am currently seeking a JavaScript function that will allow me to successfully add products to the shopping cart without the use of any frameworks.

Answer №1

What is the purpose of defining variables like

var addToCartButtons = document.getElementsByClassName('btn1')
,
var quantityInputs = document.getElementsByClassName('btn1')
, and
var removeCartItemButtons = document.getElementsByClassName('btn1')
? These queries all target elements with the same class, resulting in identical element collections being returned.

Your approach shows promise, but ensure that you assign correct classes to your elements and use consistent query selections. Storing metadata about your items in localStorage can be a useful technique. You can find more information on using localStorage here. Additionally, consider using modern syntax such as forof loops or the const keyword for improved code readability.

(() => {
  const addToCardButtons = document.querySelectorAll('.btn--add_to_cart');
  for (const btn of addToCardButtons) {
    const identifier = btn.dataset.target;

    btn.addEventListener('click', () => addToCart(identifier))
  }

  const addToCart = (id) => {
    console.log(id);
    // handle 'add to cart' functionality
  }

  // other functionalities can follow the same structure
})()
<div class="small-container">
  <div class="row">
    <div class="col-4">
      <img src="images/20 ps4.png" alt="" /></a>
      <h4>20 Playstation Store(PSN)</h4>
      <p>$20.00</p>
      <button type="button" data-target="1" class="btn btn--add_to_cart">add to cart</button>
    </div>

    <!--2-->
    <div class="col-4">
      <img src="images/25 ps4.png" alt="" />
      <h4>25 Playstation Store(PSN)</h4>
      <p>$25.00</p>
      <button type="button" data-target="2" class="btn btn--add_to_cart">add to cart</button>
    </div>

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

The Javascript/Jquery code executes just once on the initial event, doubles on the subsequent event, and continues to increase in

There is a JS function attached to an HTML button's onclick attribute: function AddFbLikes() { $('#fbform').on('submit', function(e) { e.preventDefault(); // stop form submission $("input:checkbox:checked").each(function(i ...

Generate a complete screenshot of a website using Chrome 59 through code

Is it possible to programmatically capture a full-page screenshot of a website using the latest Chrome 59 and chromedriver with Selenium Webdriver, even if the website is larger than the screen size? ...

Creating a design where the divs on the sides utilize all the available space using only CSS and HTML

I am trying to create a layout with three <div> elements - one centered at 960px width, and the other two on each side. My goal is to have the side divs take up all available space except for the 960px occupied by the centered div. I managed to achi ...

Modify the ColVis Appearance in Datatable Using JavaScript

Where can I modify the background color for the 'Hide/Show columns' label in the ColVis.js file? ...

Achieving Dynamic Center Alignment for One or Two DIVs

My goal is to create a page layout with three DIVS arranged as Left|Center|Right, while still being able to display different combinations such as Center, Left|Center, or Center|Right in the center of a wrapper div. I have been using jQuery toggle to swit ...

Can the functionality of a button be disabled after being clicked a total of 5 times?

Once a user clicks the button five times, I plan for it to be disabled. Can this be achieved solely with HTML, or would JavaScript be necessary? ...

Customizing event colors in Full Calendar

My interactive calendar is created using : $('#calendar').fullCalendar({ height: 300, //............. events: jsonData, month: firstMonth }) I am looking to dynamically change the color of an event based on certain conditions ...

Is there a solution for the issue where the :after pseudo-element on a TD in IE9 does not accurately reflect the TD height?

In the design I'm currently working on, there is a requirement for a border around a table row. Due to certain complications, using the border property directly is not an option. In trying to find a solution, I have experimented with two different app ...

Contrast the table column to a JSON object and modify a different column in an HTML file

This Dashboard is my first venture into using HTML and Javascript to create an interactive display. The table within this Dashboard showcases server names, descriptions, and time-related columns for uptime, warning, and critical statuses. To generate an A ...

Error 9 in Firebase: The function 'initializeApp' could not be located within the 'firebase/app' module

Since updating to firebase 9, I've been encountering issues with importing certain functions that were working fine on firebase 8. I've gone through the documentation and made necessary code improvements, but the error persists. This issue is not ...

Prevent dropzone from refreshing the page

For the past few days, I have been scouring the internet for solutions on how to prevent a page from automatically reloading after an upload. Despite finding various methods, I have been unsuccessful in resolving this issue. Although I am following the st ...

"Does anyone know of a specific jQuery function that allows for mapping a collection, where the `end`

I have a query that searches for specific elements within a selected area: $(some_selector_here).find("ul li.active a span") I am looking for a function that can loop through this collection of elements and provide access to the complete stack of base el ...

In bootstrap 3.0, columns are arranged in a vertical stack only

As a newcomer to web design, I've been struggling to figure out why my basic grid in Bootstrap 3 isn't working as expected. No matter what I try, my columns stack vertically instead of side by side and always resize to fill the browser window. Th ...

Having trouble getting the `transformItems` feature in React InstantSearch RefinementList to

I recently integrated the React InstantSearch library into my app and I'm working on customizing the refinement list to display only relevant filters for the active user. I attempted the following code: <RefinementList attributeName="organization" ...

One method for assigning a unique identifier to dynamically generated buttons with jQuery

<table border="0" class="tableDemo bordered"> <tr class="ajaxTitle"> <th width="2%">Sr</th> <th >SM</th> <th >Campaign</th> <th >Day1</th> <th >Da ...

centering an angular material card on the webpage

Currently, I have developed a Registration script that enables users to Sign Up on my website. However, the issue I am facing is that the angular material card, which houses the sign up interface, is not centered. Despite trying various methods such as & ...

Storing data in a text or HTML file using server-side JavaScript

Currently, I am working on a JavaScript form that involves saving user-entered variables to either a .txt file or a new webpage with the variables pre-filled in the inputs. I know that JavaScript cannot directly manipulate the user's machine, but I am ...

Transmit information using JSON format in Angular 8 using FormData

i am struggling with sending data to the server in a specific format: { "name":"kianoush", "userName":"kia9372", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bcd7d5ddd8ce85...@example.com</a>" } H ...

This video cannot be played on this platform due to its privacy settings

I'm facing a challenge with embedding my client's videos on our website. These videos have domain-level privacy settings, and I've been using the code provided by Vimeo. <div style="padding:28% 0 0 0;position:relative;"> ...

Extract information from an external website using AJAX in Laravel

On my cart page, I utilize ajax to retrieve destination information from the user and provide them with shipping options to calculate their shipping cost. While everything is functioning properly, one issue remains: I am unsure of how to iterate through t ...