Kirk Ross
Kirk Ross

Reputation: 7153

Call function if any ui dialog is opened

Let's say I have ten different dialog popups, each with their own inits and options.

How would I call a function when any of the dialog is open? i.e. the correct syntax for the following:

$(if("*").dialog("open")) $(// do this);

Upvotes: 1

Views: 1409

Answers (1)

T J
T J

Reputation: 43156

You can listen to the dialogopen event emitted by jQuery UI to execute a function whenever a dialog is opened.

For example:

$(function() {
  $(".dialog").dialog({
    autoOpen: false
  });
  $("button").click(function() {
    $(".dialog").dialog("close").eq($(this).index("button")).dialog("open");
  });
});
$(".dialog").on("dialogopen", function() {
  alert("a dialog opened!");
})
<link href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<button>Open dialog1</button>
<div class="dialog" title="Basic dialog1">
  <p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>
<button>Open dialog2</button>
<div class="dialog" title="Basic dialog2">
  <p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>
<button>Open dialog2</button>
<div class="dialog" title="Basic dialog3">
  <p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>


Or bind the listener to document on case of dynamically generated dialogs:

$(document).on("dialogopen", function() {
  alert("a dialog opened!");
});

Upvotes: 1

Related Questions