Click event on dynamically generated content

While continuing my work on playing with colours I ran into an interesting problem.

After printing the color grid on the main canvas, I wanted to add the ability for the user to remove particular colors from this grid. I was hoping to place an “X” button near the top left of every color and define a click handler to the class of these button, and just remove their parents.

It felt simple, but the initial approach I took wasn’t really working.

$(".color-remove").click(function(e){
    console.log('here');
    this.parent().remove();
});

This didn’t work. The log just won’t show up! I was stuck on this for a while , and then it hit me. The parent of '.colour-remove' is dynamically being inserted in the page’s '#canvas' and I’m attaching an event at page load. So no wonder the click handler is not getting attached!

NOTE: If you know of a way I can catch these errors faster, please do leave a comment! I’d love to learn better debugging tricks

Once I realized this could be the issue, a quick search returned back the correct answer.

JQuery Logo

We needed to use .on() methond to bind the event handler our class. (Since I’m using jQuery 1.11+, I didn’t really read through the .live() docs)

And the issue was fixed. Thanks StackOverflow!

======================================================================

Published: January 16 2015

See an error in this post? Please submit a PR on Github.