0

Thanks for your attention.

I have a DOM in which one I dynamicly insert a JS script element using :

var script = document.createElement("script");
script.id = "dynJS";
script.type = "type/javascript";
document.body.appendChild(script);

Some events later, I generate buttons in the page. Then, I add the following code in this script element to listen the click on these buttons :

$(document).ready(function(){
    $(document).on("click", "button#but1", function(){
        alert("click A");
    }
}

(respectively for the other buttons)

But the click isn't detected. Does anyone know why ?

EDIT : Problem solved.

Thanks to the comments, I fix the issue moving the delegated click listener in a code pre-existing the buttons add, avoiding the redundant script add.

Thanks a lot for the help.

  • I am not sure if the script will execute that way. – Praveen Kumar Purushothaman Jun 08 '18 at 14:56
  • Can you provide an example using the snippet button ? – Hearner Jun 08 '18 at 14:56
  • 1
    Is the JS code in your second example in the script element you append? Seems a little redundant to append the entire script when you can just use a delegated event handler - as you already are - in the DOM when the page originally loads. – Rory McCrossan Jun 08 '18 at 14:56
  • Is there some error seen in developer console? – Avezan Jun 08 '18 at 14:56
  • @j08691 Can you please let me know a better dupe? – Praveen Kumar Purushothaman Jun 08 '18 at 14:57
  • @Rory McCrossan You're right, it is redundant. So I'm gonna try to move the delegated event handler to the static script already in at the buttons loading. – Olivier GRACIANNE Jun 08 '18 at 14:59
  • @Avezan Nothing shows up. – Olivier GRACIANNE Jun 08 '18 at 15:01
  • You might be better off with a vanilla js event delegation handler. Bind the click to the body and then check to see if the event target is the one you care about. https://gomakethings.com/checking-event-target-selectors-with-event-bubbling-in-vanilla-javascript/ I'm not sure that jquery is handling that in the same way and might be attaching to the DOM elements at the time of invocation. Could be wrong though.. – dgeare Jun 08 '18 at 15:03

0 Answers0