
Introduction
Alert boxes in JavaScript are notoriously unforgiving when it comes to designing a user interface. You cannot add images, change the background color, or otherwise "theme" the dialog to match the style of your web page or web application. Fortunately, JavaScript in conjunction with the Document Object Model (DOM) is there to help us achieve an otherwise unobtainable goal.
Background
This is my second attempt at creating a JavaScript alert box. My first attempt was a few years ago. The code was buggy and difficult to use, so I put it on the backburner with the intention of doing a complete rewrite. I recently began upgrading the web application that made use of the old code, and decided that it was time to breath life into the old code.
There are a number of similar alert boxes on the web, but most are part of larger projects, or make use of external libraries.
Using the Code
To use the custom alert/dialog boxes, you must add the JavaScript source to your header, as well as the .css files that determine the "skin" the boxes will use.
<link rel="Stylesheet" href="default.css" type="text/css" media="screen" />
<script type="text/javascript" src="DOMAlert.js"></script>
If you fail to include a reference to a stylesheet, the .js file will look for default.css in the local path.
Once you have added your .js and .css files, you can create a new alert box by using the following constructor:
var msg = new DOMAlert(
{
title: 'Title',
text: 'Alert Message',
skin: 'default',
width: 300,
height: 300,
ok: {value: true, text: 'Yes', onclick: showValue},
cancel: {value: false, text: 'No', onclick: showValue }
});
The constructor takes only one argument, an object containing one or more of the following properties:
title: The title of the alert box. Can contain inline HTML, but may not render correctly. Optional. Can be passed in the show() method.
text: The text of the alert box. Can contain inline HTML, but may not render correctly. Optional. Can be passed in the show() method.
skin: The skin to use for the alert box. Skins/themes are discussed later in this article.
width: The width of the alert box. Optional, but recommended.
height: The height of the alert box. Optional.
ok: An object containing the text of the 'OK' button, the callback to be pressed when that button is clicked (onclick), and the value passed to that callback. The default is to call the close() method of the alert box. Optional, but recommended.
cancel: An object containing the text of the 'Cancel' button, the callback to be pressed when that button is clicked, and the value passed to that callback. There is no default.
Methods
The following methods are currently supported:
show(): Changes the visible state of the alert box to visible.
show(text): Changes the visible state of the alert box, and sets the text of the alert. If using this method, title must be set in the constructor.
show(title, text): Changes the visible state of the alert box to visible, and sets both the title and the text of the alert box.
hide(): Changes the visible state of the alert box to hidden.
close(): Destroys all HTML elements attached to the alert box and unregisters all the onclick callbacks. This does not destroy the object or its methods since they are prototyped.
center(): Centers the alert box on the page. Most users shouldn't need to call this, as it is called automatically.
Callback
The callbacks for the OK and Cancel buttons can either be references to an existing function or a closure. For pre-existing functions, two objects are passed as arguments, a reference to the alert box that the OnClick event was generated from, and the value of the button that was clicked.
function showValue(sender, value)
{
}
Skins/Themes
The .js file contains little to no information regarding the design of the alert box, only the layout. Since users may have different requirements in the design on a per alert box basis, and to separate design from code, the design information resides in .css files. If no skin information is provided, the code looks for a 'default.css' file to be located in the current directory. Each CSS name needs to be prefixed with the name of the skin you wish to use. So, if your theme is named 'human' and you are defining the contentArea, then your CSS name needs to be .human_contentArea.
This allows you to include all your skin information in one .css file, or in multiple ones. It's entirely up to you. However, some aspects like position or width may be overwritten in the .js file.
The following style names can be used:
alertWindow: The main alert window.
titleBar: The title bar.
titleBarLeftIcon: A div that has its style set to float: left.
titleBarRightIcon: A div that has its style set to float: right.
contentArea: The content area where your text will go.
buttonArea: The area that contains your buttons.
okButton: Your 'OK' button.
cancelButton: Your 'Cancel' button.
Bugs
IE6. Do I really need to say any more?
- IE6 doesn't support the
fixed property. If you want the alert box to stay in the center of the page if the user scrolls, you will need to add your center() method to your window.onscroll event.
Select elements will render above other elements, regardless of their z-index. The exception to this rule is an iframe. The script will check to see if you are using IE6 and if so, it will add an iframe behind the alert box to hide the select elements.
- To simulate modality and opacity, a semi-transparent .png image is used. However,
select elements can still be activated. You'll probably want to disable your select elements and re-enable them at the appropriate times.
Points of Interest
The 'filter' property in Internet Explorer has a memory leak when using 'alpha(opacity=##)', even after the owning DOM object is removed. As a result, a semi-transparent .png is used instead. This works well except in IE6, which doesn't support transparent .png files very well. Instead, I used the proprietary AlphaImageLoader when the script detects that the browser is IE6.
History
- Sunday, August 24, 2008 -- Article created.
|
|
 |
 | Problem trying to use this within an html form Dave Givens | 6:45 4 Feb '10 |
|
 |
I have tried with several browsers and method='post' and 'get', no difference. The box opens up and then immediately disappears and the 'yes' action is carried out, in my case deletion of records. Have tried it with your example amd the same problem there. If you or anyone has the answer I would be most greatful as I have spent days trying to work out what is wrong.
|
|
|
|
 |
|
 |
If you could provide some code that produces the bad results that would help. Remember that DOM alert boxes do not act like confirm or alert boxes in javascript, in that they do not "block" and wait for user input.
|
|
|
|
 |
|
 |
Below is some code that doesnt work, it is the example with a form around the button that is all.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <link rel="Stylesheet" href="default.css" type="text/css" media="screen" /> <link rel="Stylesheet" href="human.css" type="text/css" media="screen" /> <script type="text/javascript" src="DOMAlert.js"></script> <script type="text/javascript" LANGUAGE="JavaScript"> function doAlert(parent, action) { var msg = new DOMAlert( { title: '<center>Warning</center>', text: '<br><center>Do you really want to delete this message?</center>', skin: 'default', width: 300, height: 50, ok: {value: true, text: 'Yes', onclick: delValue }, cancel: {value: false, text: ' No ', onclick: showValue } }); msg.show(); };
function showValue(sender, value) { sender.close(); }
function delValue(sender) { sender.close(); submitForm(); } </script> <title>Test</title> </head> <body> <div> <form name='test'> <button name='butt' onclick="doAlert();">Test</button> </form> </div> </body> </html>
|
|
|
|
 |
|
 |
The problem is that the default action of a button inside a form tag is to submit the form. Whenever you are including javascript that needs to be run on the submission of a form, you need to short circuit the form default action. You can do this a couple of ways. Here are two that should work:
<button name='butt' onclick="doAlert(); return false;">Test</button> or
<form name='test' onsubmit="return false;">
|
|
|
|
 |
|
 |
Can't use the later as on the real app there is 20+ buttons, but the former displayed the confirm box correctly but then when selecting 'yes' I get 'Error: Object expected' against submitForm() any ideas? Thanks for you help so far it has been very helpful.
|
|
|
|
 |
|
 |
You didn't include any subroutine named submitForm(). I think what you want to do is: document.nameofform.submit(); or document['nameofform'].submit(); or document.getElementById('idofform').submit();
|
|
|
|
 |
|
 |
Thanks for all the help its all working fine now, looks so much better than standard javascript confirm and I cant use any thing than uses a java toolset as I am using mootools 1.1 on the site already.
|
|
|
|
 |
 | IE8 bug? rrnd | 4:40 6 Oct '09 |
|
 |
HI!
I've been searching for custom alert box and found this. And it's fantastic. It works well with Firefox and Chrome too, but unfortunately the IE8 has a problem with it. It places the alert box at the bottom of the page Could you help me? I tried to modify the isIE6 to true, but I had the same result. Any advice would be appreciated! Have a nice day!
Best regards Gábor
|
|
|
|
 |
|
 |
Sadly I don't have access to IE8 to test. This code isn't my best work and I've learned a lot since I wrote it, so I don't know if I would necessarily use it. Have you considered using something like the prototype windows at http://prototype-window.xilinus.com/[^]? They probably will meet your needs and are better equipped to work across multiple browsers.
Also, make sure you are using an XHTML strict doctype for my code. It probably won't work well without it.
modified on Tuesday, October 6, 2009 10:23 AM
|
|
|
|
 |
|
 |
Thank you for the tip! Have a nice day!
|
|
|
|
 |
 | Urgent Help Helbrax nagarajgandhi | 4:37 26 Mar '09 |
|
 |
Hi Helbrax
Your comment on IE bug:
IE6 doesn't support the fixed property. If you want the alert box to stay in the center of the page if the user scrolls, you will need to add your center() method to your window.onscroll event.
can you tell me how to do this thing.. please
let me know asap.
Ur code its excellent it helped me lot..
Thanks and regards
Nagaraj gandhi
|
|
|
|
 |
|
 |
window.onscroll = YourAlertBoxObject.center; window.onresize = YourAlertBoxObject.center;
window.onscroll = function() { YourAlertBoxObject.center(); }; window.onresize = function() { YourAlertBoxObject.center(); };
Thanks for you remarks. I don't think the code is all that great. I can do better. One of these days I'm gonna rewrite it, but not today!
|
|
|
|
 |
 | Hi Herbrax nagarajgandhi | 1:13 18 Mar '09 |
|
 |
Hey Herbrax
Your program is excellent .... thank you so much
|
|
|
|
 |
 | alert not working on page with frame and header annese | 16:00 20 Nov '08 |
|
 |
hi..can u please help me to solve my problem. this alert is not working on page with frame and header. the alert box is not focus at all, and i can still can click (using mouse) on behind page on the frame side and also the header side (for hyperlink). thanks
|
|
|
|
 |
|
 |
The alert doesn't play well with frames usually. If you can send me a sample that recreates the problem I can take a look at it.
|
|
|
|
 |
 | Are frames keeping this from working for me? luaprentoc | 17:45 14 Sep '08 |
|
 |
I configured the code to produce a custom alert box like I wanted using a test HTML file. I then transferred the code to my project, a quiz. I was going to use the custom alert box to tell the person they answered the question correctly. However, in my project I can't get the custom alert box to show (I could in my test file but not in my project). Is it because in my project the page from which the doAlert function is called is in a frame? I've tested in Firefox 3.0.1 and IE 7.0.5730.11 Thanks
|
|
|
|
 |
|
 |
More than likely. I have tested the code in a "cross page/frame" environment and I'm not sure it would work all the well, since it's centering would be screwed up and it would be incapable of overlapping the other frames.
|
|
|
|
 |
 | Outstanding! dpminusa | 10:32 26 Aug '08 |
|
 |
That would make the three of them non-braindead at last!
"Coding for fun and profit ... mostly fun"
|
|
|
|
 |
 | Mod for Prompt also? dpminusa | 10:11 26 Aug '08 |
|
 |
Alert is great. What about a mod so this can be used as an alert, confirm, or prompt. IE Prompt is a pain as it is now.
"Coding for fun and profit ... mostly fun"
|
|
|
|
 |
|
 |
It shouldn't be too difficult to render something like that.
|
|
|
|
 |
 | Yaah ... this one is using IFrame Abhishek sur | 22:40 24 Aug '08 |
|
 |
Its old one. We been using this popup alert thing for long time... anyways .. good one ... good to have one simple just adding one js file...
Abhishek Sur
|
|
|
|
 |
|
 |
Thanks. The IFrame hack should only be used on IE6. It's a stupid hack, but then again, IE6 is a stupid browser. 
I've used other alert windows in the past. Some were either highly configurable(and bloated) required you to make code changes for configurability(you end up with 2+ .js files) or were part of larger libraries or modules.
I wanted to make something that was light weight, but still could still be configured easily, at least the design portion.
|
|
|
|
 |
|
 |
yes... its light weight...
and wonderful... so simple.. u've done a great job
Abhishek Sur
|
|
|
|
 |
|
|