27 May 2012

DialoguePane.js: a modal dialogue box for a web page

I was looking around on the web for a simple way of displaying a modal dialogue box over a web page. There are lots of options, but none of them seemed to work the way I wanted, so I wrote my own.

Click here to download a demo of DialoguePane.js as a ZIP file. API documentation is included.

A DialoguePane object is mainly the state of the title, body, and buttons of a dialogue box. The title and button labels are just plain text, and the body is typically a string displayed using the innerHTML element of the body. Alternatively, you can display a HTML element that you have built yourself or that you have lifted from another part of the document. If you can't be bothered customising the dialogue too much, there are two convenience functions that can display a dialogue in a single call, presuming a lot of default behaviour.

When you want to show the dialogue, the object turns this state into a HTML element consisting of nested div elements and adds the root of these elements to the document tree. CSS styling covers the entire window with a translucent pane to prevent mouse clicks behind the dialogue.

Each time a dialogue appears, it can either be confirmed or cancelled - that is, it can be used to ask yes/no questions. This can be left out if you are just displaying a dialogue box with a message. Developers can specify callback functions to customise what happens in response to each of these actions, and both actions can also have callbacks that can prevent the dialogue from being dismissed, for example, if the user input is not correct. The user can dismiss the dialogue either by clicking one of the buttons or by pressing Enter or Esc (to confirm or cancel the dialogue).

It's taken a fair bit of tweaking to get this to work more or less identically across a bunch of different browsers. So far, I've tested DialoguePane in Firefox 12.0 and Safari 5.1.7 on my Mac and in Internet Explorer 8 on Windows. It also works in Internet Explorer 10 on a Windows 8 VM, using the F12 Compatibility Tools to emulate IE8, IE9 and IE10. Note that JQuery is not required.

I'm not putting any restrictions on the use of this code; I just wanted to try to build something simple and useful. Likewise, although I'll be using this in a project I'm working on at the moment, I'm not making any guarantees that this will be right for your project.

No comments: