1

I'm creating a simple shopping cart with javascript, and what would a shopping cart without a button to remove an item be?

The cart is created on-the-fly with javascript, so the elements won't exist on page load. However, this shouldn't be a problem with this?

$(".removeFromCart").on("click",function(e){
    alert("GO AWAY PLEASE..");
    var tuoteID = $(this).attr("data-id");
    deleteFromCart(tuoteID);
});

The element (created on the fly) simply looks like this:

<a href="#" class="removeFromCart" data-id="2">×</a>

But it won't trigger. If I replace .replaceFromCart with, for example, p, it will trigger every time I click on a paragraph.

This isn't the first time I'm having problems with .on() and it always takes half of my hair to solve, so maybe someone with more experience could point me what I'm doing wrong.

  • 1
    This question has been asked more times than i can remember. – Patsy Issa Mar 06 '14 at 08:41
  • @PatsyIssa probably, but english isn't my native language, so it isn't that easy to always find the right words to find the right results. I did find a couple of solutions with `.live()` or similar. –  Mar 06 '14 at 08:43
  • 1
    As you write the question SO shows you suggestions about similar questions, keep an eye out for it ^^ – Patsy Issa Mar 06 '14 at 08:44

1 Answers1

2

You need event delegation, using other version of the jQuery on() function. You have to give the static parent that is present the time the binding code is executed or you can delegate to body or document.

$(document).on("click",".removeFromCart", function(e){
    alert("GO AWAY PLEASE..");
    var tuoteID = $(this).attr("data-id");
    deleteFromCart(tuoteID);
});

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers, jQuery doc.

Adil
  • 146,340
  • 25
  • 209
  • 204
  • Thank you! Where I would be without stackoverflow... –  Mar 06 '14 at 08:41
  • 2
    @Christian On jQuery Docs – Mr. Alien Mar 06 '14 at 08:45
  • @Mr.Alien On jQuery docs I see a ****load of text, filled with words that I won't encounter so often. It has a lot of examples but it's rare to find an example I can directly use ;) –  Mar 06 '14 at 08:58