BehaminB BehaminB - 4 months ago 27
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?

<html>
<head>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<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>');
});
} );
</script>
</head>
<body>
<div id="dialog" title="Basic dialog">
<p>This is a basic dialog</p>
</div>
<button id="opener">Original Opener</button>
<button id="ContextButton">Add context</button>
</body>
</html>

Answer

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.

Comments