Adam Adam - 2 years ago 57
HTML Question

how to make a jQuery event apply to all selected elements including the ones added as a consequence of the event?

I want to create a function that adds a h1 for each h1 clicked, I have coded one that works, but it only works with the original h1, and the newly added h1s do not generate anything when clicked.

$("body").after("<h1>this is an added header</h1>");

Answer Source

You're best using a delegated event for this:

$("body").on("click", "h1", function(event){

Basically, there's only one event handler on the body that's firing if a click event happens from within a h1 tag. It's inefficient to repeat the same listener multiple times across different elements, especially when you need future elements to trigger that behaviour too. That's precisely one of the reasons why delegated handlers exist.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download