How to add a dialog box with jQuery and make it show more than once?

Sometimes, we want to add a dialog box with jQuery and make it show more than once.

In this article, we’ll look at how to add a dialog box with jQuery and make it show more than once.

How to add a dialog box with jQuery and make it show more than once?

To add a dialog box with jQuery and make it show more than once, we can use the jQuery UI’s dialog method with the modal option set to true.

For instance, we write:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" />

<button>
  show
</button>

<div id="dialog" title="Basic dialog">
  <p>hello world.</p>
</div>

We add the show button and a div for the dialog.

Then we write:

$(() => {
  $("#dialog").hide()

  $('button').click(() => {
    $("#dialog")
      .dialog({
        modal: true,
      })
  })
});

We select the dialog div with $("#dialog").

And we call hide on it to hide it initially.

Then we select the button with $('button').

And we call click on it with a callback that calls dialog with an object with modal set to true.

Now when we click the button, we see the dialog displayed. And we can close it with the ‘x’ button and click show to open it again.

Conclusion

To add a dialog box with jQuery and make it show more than once, we can use the jQuery UI’s dialog method with the modal option set to true.