Page 1 of 1

Message box Rate Topic: -----

#1 ahmad_511   User is offline

  • MSX
  • member icon

Reputation: 131
  • View blog
  • Posts: 722
  • Joined: 28-April 07

Post icon  Posted 21 July 2009 - 11:14 AM

Hello everyone.
I was working on an Intranet application for the company I'm working for, and using the alert message wasn't enough, especially that we (in some cases) need to have multiple decisions to be taken according to that message, besides it doesn't fit the main page style.
for that reasons, I created what I think is useful in my case and I hope it will be useful to you as well..

So,In this tutorial we will try to create our own (alert) Message box,

Whatís the different?
You may say: itís easy to create a stylish div element, give it an absolute position and a high z-index value.
Ok, youíre right, but, this is not the case when we need to disable all other items behind that div which will prevent users from interacting with the page contents until he responds to what this message is asking for, and also hold executing some code blocks until user responds to the message box .

The Ideas behind:
1-disable all page contents
This is the easiest thing, all what we need is to cover all of the pageís contents with a div (it may be transparent or semi transparent if you want) which will receive all events instead of the page contents

2- Holding the execution process!
neh, I didnít say that, I said hold executing some codes till user respondsÖ.
since weíre sure now that user canít interact with the other contents on the page (thanks to the div cover), Iím thinking to create a separate function which will contain all scripts we need to execute if a user clicks a button on the message box

Note: If you reach this line and youíre yet getting bored, prepare yourself for the worse :D

What you should know before you continue?
-A little bit of HTML.
-Intermediate skills in CSS.
-Intermediate skills in javascript.

We will work on three files: msgbox.js, msgbox.css, msgbox.html, and we need some pictures too.
Letís start working on javascript first to accomplish the two ideas mentioned before.

java script:
Two functions are needed, the first one msgbox() will handle the creation of the message box, and the second one closemsgbox() will handle the interactions and then close the message..

msgbox() function:
This function accepts two required arguments (caption,message) and two others optional(buttons ,resfunc)

caption: is a string represents the messageís title (can be html string).
message: is a string that contains the messageís body (can be html string).
buttons: is a comma separated string, each part of it will create a new button on the message box (whatever you pass it will create a button with the same name, so no pre-defined set of buttons are required)
refunc: is a function reference to be executed when user clicks a button (this function receives the buttonís value which is the same of the buttonís name you pass to be checked inside the resfunc function)
This is how it looks for now:
function msgbox(caption,message,buttons,resfunc){
// create a fake response function if not passed
if(resfunc==undefined)resfunc=function(){return false;};

Creating the covering div:
Letís create it and append it directly to the documentís body (its style will be covered later on CSS part)
In the following code we create a new div, assign it a class name by using className property and setAttribute method to ensure it will work on IE as well as on FF.
var disablediv=document.createElement("div");

Crating the message box:
The message box contains three paragraphs (first is for the title and the close button, second is for the messageís body, and the third is for the buttons group)
Attached Image

So, we create another div (msg) to hold all of the message box paragraphs.

Letís add two new properties to the message div itself to refer the response function and disablediv element (doing this will allow us to call multiple messages to popup at the same time keeping each message related to its callback function and its relative disablediv

Declaring strHTML var to hold the compiled HTML code, adding the messageís title and include the "caption" argument into it.
var strHTML="<p class='msgboxtitle'><span class='caption'>"+caption+"</span>"
// adding the close button image, onclick event will be discussed later while creating the second function.
strHTML +="<img src='close.png' class='close' onclick=closemsgbox('btn_msgClose',this.parentNode.parentNode) /></p>"
//adding the message body paragraph and include the message parameter
strHTML +="<p class='msgboxdesc'>"+message+"</p>";
//  assign the compiled HTML to the div msg

Creating the buttonís group holder paragraph:
// buttons argument is optional, so, we need to check if itís passed or not in order to continue creating those buttons
if (buttons!=undefined){
//converting the comma separated string into Array (btnArr) using (,) as delimiter
var btnArr=buttons.split(",");
// create a new paragraph (btnGrp) to be used as a container for the buttons
var btnGrp=document.createElement("p");

Letís add the buttons now:
We have an array of buttonís names, so weíll read that array and create those buttons
// we do a descended loop because the CSS right align property will reverse its sequence order.
for (i=btnArr.length-1;i>=0;i--){
// create a button element
var btn =document.createElement("input");
// give it a value to be used as display text and 
// add onclick event to the button
// append the created button to the buttons group

Once the loop ends the buttons group will be ready, so we append it to the msg div, after doing that, the message will be ready to be added to the documentís body.
// append the message
return msg;

closemsgbox() function:

Almost done, we still have to create the response handling function (closemsgbox) which is very simple.
This function accepts two arguments, the clicked buttonís value, and the message box div object that contains the clicked button.

Remember that we already added two properties to the message div object (disablediv, resfunc)? Now is the time to use them.
if you take a look back to the image we included into the message box as a close button and to the other buttons we added to handle user interactions, youíll find that we always passing the buttonís value (in case if the message close button itís fixed value"btn_msgClose") and parentNode.parentNode which is referring to the msg div element in both cases (all of them are second level children to the msg div)
function closemsgbox(btnval,msgobj){
// calling the response function using its reference (msgobj.resfunc) and pass it the clicked button value and the message box object
//removing the disable div element by using its reference (msgobj.disablediv)
// removing the message box itself

Weíve done the javascript, so get yourself a cup of coffee and get readyÖ

Styling the message box elements:
Since itís a javascript tutorial, Iíll just mention what are required and what are not

- filer,-moz-opacity not required
- top, left, height, width donít change
- z-index you can change it as required but it has to has a value greater than all other elements on the document and less than the dvmsgboxís z-index, it must cover the page and not the message box

position, top, left, margin-left, margin-top donít change unless you like to specify another position rather than center
z-index it must has a value greater than the disabledivís z-index
background:silver url(msgbox.png) no-repeat left top;

Note: you can use the combination of position,top,left,margin-left,margin-top to center any element vertically and horizontally without the need of any kind of scripting, so you may want to use it in different place

msgboxtitle, caption, close:
float, clear required
All others can be changed (I just adjusted them to go with my messageís background design)
.dvmsgbox .msgboxtitle{
margin:2px 4px 0px 2px;

.msgboxtitle .caption{

.msgboxtitle .close{

float, clear, white-space required
.dvmsgbox .msgboxdesc{
margin:5px 4px 0px 2px;

All can be changed
.dvmsgbox .msgboxbuttons{
margin:2px 4px 0px 2px;

msgboxbuttons input[type="button"]:
float, clear, position required, all others are not
.dvmsgbox .msgboxbuttons input[type="button"]
background:Silver url(msgboxbuttons.png) repeat-x;
border:solid 1px #003C74;	
padding:0px 2px 2px 2px;
margin:0px 0px 0px 4px;

CSS done, all what we need now is tree PNGs (or whatever is the picís type since you know youíre doing).

msgbox.png is the message title/body background (301px, 171px), if you want to change the size, make sure to update your CSS as required.
close.png represents the title bar close button
msgboxbuttons.png is the background for the messageís buttons.
You can download the attached file which contains all necessary files

How to use:
Note: this code has been tested on IE7/IE8 Standard mode, FF3.5 Beta 4, Chrome

1- Passing the first two arguments: no buttons set / no callback function
var a=msgbox("Warning","Hello there, you made a big mistake by running this...");

The result will look like this:
Attached Image

2- Passing the buttons set argument: this will be useless without a callback function unless you want to have just OK button for example.
var b=msgbox("Info","Your request has been sent successfully","Ok");

Attached Image

3- Passing the callback function reference: the passed function will be executed when a user clicks any button on the message box, and as mentioned before this function receives two arguments: the buttonís value and the message box div object which contains the clicked buttons.

Note: we pass the message box div object to have the benefits of adding user defined properties/methods as the process required
var c=msgbox("Note","Are you sure you wanna do this?","Yes,No,Cancel",ccallback_func);

function ccallback_func(btnval){
	alert("you clicked ["+btnval+"] Button")

Attached Image

4- Adding a new property to be passed the callback function: it may happen that you want to pass a few variables to be processed inside the callback function with the need for declaring a global scope variable, besides in this way you can define the same property name for a multiple message boxes but with a different value without worrying about overriding issues.
var d=msgbox("Overloading","We will pass two new variable's values through two new property (myVal1='Red',myVal2='Blue')","Option1,Option2,Cancel",dcallback_func);

function dcallback_func(btnval,msgobj){
	switch (btnval){
		case "Option1":

		case "Option2":

		case "Cancel":
			alert("You clicked [Cancel] button")

Attached Image

5- Adding other HTML elements inside the message and targeting it: this is simply can be done by inserting HTML string containing the elements you need in the messageís body
In the following example weíre adding a textbox to the messageís body, and then weíre assigning the textbox object itself to a new property (myname), after that inside the callback function weíre reading this objectís value.
var e=msgbox("Greeting","hello this is me!<br />type your name here:<input type='text' id='inputName'/>","Ok,Cancel",ecallback_func);
function ecallback_func(btnval,msgobj){
	alert("your name is "+msgobj.myname.value);

Attached Image

Thatís it,
I hope you found something useful here and I didnít waste your time.

You can download the three files here (including the pics)Attached File (12.48K)
Number of downloads: 3134

any comments or suggestions are welcome
Thanks for your patience.

Is This A Good Question/Topic? 2
  • +

Replies To: Message box

#2 born2c0de   User is offline

  • printf("I'm a %XR",195936478);
  • member icon

Reputation: 187
  • View blog
  • Posts: 4,673
  • Joined: 26-November 04

Posted 22 July 2009 - 08:43 AM

Nice work.
Was This Post Helpful? 0
  • +
  • -

#3 mm_farahat   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 01-May 10

Posted 01 May 2010 - 11:34 PM

good work , thnx
Was This Post Helpful? 0
  • +
  • -

#4 arvindthakur   User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 133
  • Joined: 07-June 11

Posted 09 June 2011 - 12:32 AM

very good work ahmad....
Was This Post Helpful? 0
  • +
  • -

#5 ahmad_511   User is offline

  • MSX
  • member icon

Reputation: 131
  • View blog
  • Posts: 722
  • Joined: 28-April 07

Posted 20 June 2011 - 06:53 PM

Hello and thanks,

I recently updated this old message box to fit a project I was working on, and here is what changed:

1- new style using a simple image sprite.
2- buttons are now passed as an array of object: [{c:sCaption,e:fFunction,d:oDataObject,a:bAcceptButton},...]
3- specifying the accept button (the button to be clicked if you hit [Enter] key)
4- enabling escape key to close the message

here is the new look:
Attached Image


1- Normal use
msgbox("Example 1","Hello,<br />This is a normal message");

2- Adding buttons
msgbox("Example 2","Message with buttons",

function ex2_yes(){

function ex2_no(){

3- Specifying the accept button
msgbox("Example 3","Specify the accept button<br />See focused button<br />Hit [<span style='color:orange;'>Enter</span>] key",
		{c:"Button 1",e:ex3_def},
		{c:"Button 2",e:ex3_def,a:true},
		{c:"Button 3",e:ex3_def}

function ex3_def(d){
	alert("You clicked "+d);

4- Passing data to the button's event handler
msgbox("Example 4","Passing data to the button's event handler",
		{c:"Option 1",e:ex4_opt1,d:"Hello there"},
		{c:"Option 2",e:ex4_opt2,d:"How are you?"},
		{c:"Option 3",e:ex4_opt3,d:"Hope you're Ok"}

function ex4_opt1(d){

function ex4_opt2(d){

function ex4_opt3(d){

you can try it here message box2
finally this the code(including examples shown above)Attached File (8.04K)
Number of downloads: 942
Was This Post Helpful? 2
  • +
  • -

Page 1 of 1