Avg. Rating 3.0

Problem

Usually when talking about a modal window in JavaScript the solution is to cover the background and open an HTML div on top. But what if you want to open a real modal window.

Solution

By tweaking the initial options and handling some of the nativeWindow events you can easily make any window modal.

Detailed explanation

Start by opening a window, that doesn't have the minimize and maximize system chrome; you don't need them on a modal dialog window.

var options = new air.NativeWindowInitOptions();
var modalWin = null;
var width = 450;
var height = 250;
var bounds = new air.Rectangle(

    (air.Capabilities.screenResolutionX - width) / 2,
  (air.Capabilities.screenResolutionY - height) / 2,
  width, height);

options.type = air.NativeWindowType.NORMAL;

modalWin = air.HTMLLoader.createRootWindow(
   true, options, true, bounds
);
   
modalWin.load(new air.URLRequest(
    "modalWin.html"
));


You will need to prevent the window from closing, deactivating, and loosing the keyboard focus. You can call a method to do that from inside the window when the window content is loaded. Add the following line to the end of the code that opens the modal window:

modalWin.addEventListener(
  air.Event.COMPLETE ,
  function (e) {e.target.window.makeWindowModal()} 
);


Finally, implement the makeWindowModal function in modalWin.html. There are very few things that must be handled actually:

function makeWindowModal() {
    nativeWindow.activate();
    nativeWindow.alwaysInFront = true;
    nativeWindow.addEventListener(
     'deactivate',
     function (e) {nativeWindow.activate()}
    );
    nativeWindow.addEventListener(
     'displayStateChanging',
     function (e) {e.preventDefault()}
    );
    nativeWindow.addEventListener(
     'closing',
     function (e) {e.preventDefault()}
    );
}

That's it. You now have a window that stays on top, can't loose focus, and can't be closed. That's pretty modal alright.

Just don't forget to add a close button in modalWin.html, otherwise there will be no way to close the whole application. A simple window.close() will do just fine:

<input type='button' onclick='window.close()' value='Close' />
 


+
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes