0

I'm working to learn javascript by building a basic fruit shopping page where fruits displayed at the top of the screen can be clicked on and added to a "cart" at the bottom of the screen. Once a fruit is in the cart, clicking an image should remove it from the cart.

Clicking to add an image is working fine, but clicking to delete the image is not, even though the code is basically the same.

Using debugger and some console.logs, I've identified that the click event is the issue, as opposed to the function associated with it.

I've tried changing the html selectors to see if that were the issue, as well as changing the order of the functions in the document.ready statement.

$(document).ready(function() {
    renderInventory();
    addFruitOnClick();
    removeFruitOnClick();
    render();
});

This code is working to add fruits to the cart:

function addFruitOnClick () {
    $("#inventory img").on("click", function(event) {
        OWNED_FRUIT.push(event.target.id);
        render();
    })
}

This code is not working to remove fruits from the cart:

function removeFruitOnClick () {
    $("#cart img").on("click", function(event) {
        OWNED_FRUIT.splice(parseInt(event.target.id, 10), 1);
        render();
    })
}

Here's the relevant html:

<body>
        <div id="inventory"></div>

        <div id="cart"></div>

    <script src="index.js">

    </script>
    </body>
Austin
  • 3
  • 1
  • Your html snippet does not have children for the inventory or the cart. So it's unclear if you are doing your binding before they are created or not. – Taplar May 23 '19 at 15:28
  • `$("#cart img")` does not exist when you attempt to bind the event handlers. You need to use a delegated event handler instead, ie `$('#cart').on('click', 'img', function() ...`. See the duplicate for more details – Rory McCrossan May 23 '19 at 15:29
  • Save for the `inventory` binding as well, though the question says that one works, which is confusing. – Taplar May 23 '19 at 15:32

0 Answers0