There comes a time in every web developer’s life when you need to show a popup to a user. Not like a popup window, but a message box. For the non-particular user, the good old alert(strMessage) can do the job. However, alert has some drabacks – it cannot display HTML, you cannot set the title of the dialog, you cannot change the icon, etc.
Another alternative frequently referenced is to use window.open(…). I am not a fan of this approach, as it runs into popup blockers and does not create a reliable effect across browsers.
So, I ventured to wrtite my own quick-and-dirty message box. The idea is to use DHTML, and to dynamically create the message box when a method is called. Basic features include:
- Ability to set title
- Ability to set icon (Info, Warning, Error)
- Ability to pass HTML encoded content as text
Here is a quick test:
That’s about it. Nothing fancy. Integration is pretty straight forward:
- add script reference
- add CSS reference
- call ccMessageBox.Show function inline
Here is the button code:
<input onclick="ccMessageBox.Show('ccMessageBox', 'This is a message area. Text can be <em>styled</em> via<strong>html</strong>!', 'Info', 400, 100, null); " type="button" value="Show Popup" />
About the code
Basically, two major components to this script – js file and css (including some images).
ccMessageBox.js – The code implements a singleton class the primary methog of wich is “Show(…). The method dynamically instantiates a DIV on the page and shows it to the user.
ccMessageBox.css – contains styles used to create a message box feel.
Creates a displays a message box with specified paramters:
- strTitle: title of the message box
- strText: HTML text that should be displayed
- strType: string representing the message type: “Info” or “Error” or “Warning”
- iWidth: width in pixels
- iHeight: height in pixels
- strOnClose: any custom on-close handling (i.e. document.getElementById(’email’).focus(); )
the strOnClose argument can be used to perform additional actions once the dialog is closed.
Code is fairly documented, so check there for explanation of how it works.
- 0.1 – Initial Revision
- 0.2 – Update (2010.03.27): fixed the positioning such that the message box is displayed in the middle of viewable browser area. The class now calculates the center of browser display area regardless of the scroll and places the message box in the center. Prior version used clientWidth/clientHeight properties, which potentially places the message box outside of visible area.