0

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>

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.