0

I'm trying to set up click event registration for initially loaded 'link' class div's plus any others that the user will add later within the 'linksPanelHdr' div. I've studied the existing SO answers on how to do this but I must be missing something basic.

With this html:

<div class="linksPanelHdr">
    <div id="171" class="link">
        <span class="delButt">Delete Link</span>
        <span class="openButt">Open Link</span>    
    </div>
</div>

and with this jq:

$(".linksPanelHdr").on("click",".delButt",function(){ 
    alert("Triggered by link"+$(this).parent().attr('id'));
});

As I understand it this jq should trigger the alert when any 'delButt' class element that's a descendant of any 'linksPanelHdr' class element in the dom is clicked. But Firefox Inspector shows that the event is not registered either when it's in the initial load or if it's in a link that's added dynamically. And of course the click event fails to fire.

If I replace the .delButt selector with 'null' the event fires when I click inside the 'linksPanelHdr' div. Can anyone tell me where I'm screwing up? Thanks in advance.

Banjobum
  • 57
  • 8

1 Answers1

0

Before posting I did some more reading. Esp I reread SO: Event binding on dynamically created elements?.

In there I noticed in the example:

$(staticAncestors).on(eventName, dynamicChild, function() {});

I was using a non-static ancestor for the first selector . i.e. I was trying to register the event on a div up the tree that could have been dynamically added. I don't know how jq would know that but that solved the problem in any case.

I see now that the main selector should be the first element up the tree that encloses the specific (dynamic) selector target. I believe you want to get that first static element up the tree in order to minimize bubbling time - so don't just go up to 'body' which will always be static. Hope this might save some time for others who might run into this same situation which I totally missed.

Community
  • 1
  • 1
Banjobum
  • 57
  • 8