BehaminB BehaminB - 3 months ago 8x
Javascript Question

jQuery Open Dialog From Added Script

I created a very simple example of my problem. So I have a button (Add context) that adds some html to body, in fact the html here is a button (Added Opener) that should open a simple jquery dialog. However it will not work because at this point DOM ready is already executed. I added another button (Original Opener) which is executed before DOM is ready and that button works fine. My question, how can I make Added Opener button to work so it can open a dialog after DOM ready?

<script src=""></script>
<script src=""></script>
$( function() {
$( "#dialog" ).dialog({
autoOpen: false

$( "#opener" ).on( "click", function() {
$( "#dialog" ).dialog( "open" );

$( "#ContextButton" ).on( "click", function() {
$("body").prepend('<button id="opener">Added Opener</button>');
} );
<div id="dialog" title="Basic dialog">
<p>This is a basic dialog</p>
<button id="opener">Original Opener</button>
<button id="ContextButton">Add context</button>


Use on delegated event for dynamically added elements.

$('body').on("click", "#opener", function() {
     $( "#dialog" ).dialog( "open" );

I would recommend you to go search for similar kind of issues(in stackoverflow) first before posting a question. Anyways Please search for it again so that you know why do we have to use delegated event.