jQuery Project - Quick Question

Hello everyone! I have the page pretty much built, except I am trying to make the ‘add to cart’ work. I have included a Codepen link . https://codepen.io/tyler308956/pen/rNKLKrG


  1. I’m trying to create a variable to count the items in the shopping cart and initialize it to zero.

  2. Create a variable to hold some html to create a delete button. You can use a span tag with a class of ‘del’ and text Remove

What I am confused with:

  1. I know how to ‘create a variable’; however, creating a variable that ‘count[s] the items in the shopping cart’ is throwing me off.

  2. I have created a variable (see Codepen link above) that has html to create a delete button. Is that correct?

Create an array of shopping cart items, initialise to an empty array

Whenever someone clicks an item

Push that item to the array

Then the count of the items in the shopping cart is the length of that array

Is there a specific reason you want to insert html with JS rather than having the delete button present in the html and manipulating the css display value with JS?

So like:

const shoppingCart = [];

    $('.add').on('click', function () {

Yes but pass event to the callback and use that value

  let shoppingCart = [];
    $('.add').on('click', function (event) {

If you use this code and look at your console, you’ll see that cart item ids are added to the shoppingCart array when you click add to cart.

Then use shoppingCart.length to get the total count

Finally got it!!

$(document).ready(function () {

    let shoppingCart = 0;

    $('.add').click(function () {
        let itemName = $(this).attr('name');
        let itemID = $(this).attr('id');
        if (shoppingCart > 0) {
        let cartLink = `<li class='cartItem' name='${itemID}'>${itemName} <span class='del'>Remove</span></li>`;
        $('#' + itemID).hide();

        $('.cartItem').on('click', function () {
            $('#' + itemID).show();
            if (shoppingCart === 0) {


    //mouseover event to all images on page
    $('body').delegate('img', 'mouseover', function () {
        $(this).css('border', 'LawnGreen 2px solid');
    // mouseout event to all images on the page
    $('body').delegate('img', 'mouseout', function () {
        $(this).css('border', 'cornsilk 2px solid');
    // let deleteButton = `<button type='button'></button>`;
    // $('.add').on('click', function () {

    // })

}); // END READY

The only problem now is that whenever I click “add to cart” and remove it from the cart, it still shows “your cart is empty” lol