I create a button:
var removeButton = document.createElement('button');
$(removeButton).attr('class', 'removeProduct');
$(removeButton).append(document.createTextNode('X'));
$(removeButton).data('divId', 'productLine' + numProductsInCart);
This works, the button appears.
However, when I try to produce an alert on that button being clicked it doesn’t work. I click the button and it doesn’t do anything.
Here is what I have got to so far:
$('.removeProduct').click(function() {
alert("Hey");
});
I am assuming you are attempting to bind the event handler before your add your button to the DOM. If that’s the case, you need to delegate the event handler higher up the DOM tree:
This works because DOM events tend to bubble up the tree from the element at which they originate. You can capture the event at any ancestor element. The
onmethod will check whether the event target matches the selector, and run the event handler if so. Note that if you’re using a version of jQuery below 1.7 you will need to usedelegateinstead ofon.Alternatively, you could bind the event handler after you’ve created the element: