Page 1 of 1

Message box Rate Topic: -----

#1 ahmad_511  Icon 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");
disablediv.className="disablediv";
disablediv.setAttribute("class","disablediv");
document.body.appendChild(disablediv);



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.
msg=document.createElement("div");
msg.className="dvmsgbox";
msg.setAttribute("class","dvmsgbox");


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
msg.disablediv=disablediv;
this.msg.resfunc=resfunc;


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
msg.innerHTML=strHTML;



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");
btnGrp.className="msgboxbuttons";
btnGrp.setAttribute("class","msgboxbuttons");


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");
btn.type="button"
// give it a value to be used as display text and 
btn.value=btnArr[i];
// add onclick event to the button
btn.setAttribute("onclick","closemsgbox(this.value,this.parentNode.parentNode)");
// append the created button to the buttons group
btnGrp.appendChild(btn);
}


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.
    msg.appendChild(btnGrp);
}
// append the message
document.body.appendChild(msg);
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
msgobj.resfunc(btnval,msgobj);
//removing the disable div element by using its reference (msgobj.disablediv)
document.body.removeChild(msgobj.disablediv);
// removing the message box itself
document.body.removeChild(msgobj);
}



CSS:
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

disablediv:
- 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
.disablediv{
background-color:black;
position:fixed;
top:0px;
left:0px;
z-index:1005;
height:100%;
width:100%;
filter:alpha(opacity=70);
-moz-opacity:.7;opacity:.7;
}



dvmsgbox:
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
.dvmsgbox{
position:absolute;
z-index:1006;
padding:0px;
margin:0px;
width:301px;
height:171px;
background:silver url(msgbox.png) no-repeat left top;
top:50%;
left:50%;
margin-left:-150px;
margin-top:-85px;
}



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{
width:295px;
margin:2px 4px 0px 2px;
padding:0px;
color:white;
font-family:verdana;
font-size:14px;
font-weight:bold;
line-height:26px;
height:26px;
vertical-align:middle;
float:left;
clear:none;
}

.msgboxtitle .caption{
float:left;
clear:right;
width:275px;
}

.msgboxtitle .close{
cursor:pointer;
margin-top:3px;
} 



msgboxdesc:
float, clear, white-space required
.dvmsgbox .msgboxdesc{
width:295px;
height:112px;
font-family:verdana;
font-size:12px;
font-weight:normal;
padding:0px;
margin:5px 4px 0px 2px;
color:black;
float:left;
clear:none;
vertical-align:top;
white-space:pre-line;
} 



msgboxbuttons:
All can be changed
.dvmsgbox .msgboxbuttons{
width:295px;
padding:0px;
margin:2px 4px 0px 2px;
float:left;
clear:none;
}



msgboxbuttons input[type="button"]:
float, clear, position required, all others are not
.dvmsgbox .msgboxbuttons input[type="button"]
{
font-family:verdana;
font-size:12px;
width:auto;
height:18px;
background:Silver url(msgboxbuttons.png) repeat-x;
border:solid 1px #003C74;	
padding:0px 2px 2px 2px;
margin:0px 0px 0px 4px;
position:relative;
cursor:pointer;
float:right;
clear:left;
text-align:center;
vertical-align:middle;
} 



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 3.0.182.3

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);
d.myVal1="Red";
d.myVal2="Blue";

function dcallback_func(btnval,msgobj){
	switch (btnval){
		case "Option1":
			alert(msgobj.myVal1)
		break;

		case "Option2":
			alert(msgobj.myVal2)
		break;

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


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);
e.myname=document.getElementById("inputName");
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  msgbox.zip (12.48K)
Number of downloads: 2155

any comments or suggestions are welcome
Thanks for your patience.

Is This A Good Question/Topic? 2
  • +

Replies To: Message box

#2 born2c0de  Icon User is offline

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

Reputation: 180
  • View blog
  • Posts: 4,667
  • Joined: 26-November 04

Posted 22 July 2009 - 08:43 AM

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

#3 mm_farahat  Icon 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  Icon 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  Icon 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

Examples:

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



2- Adding buttons
msgbox("Example 2","Message with buttons",
	[
		{c:"Yes",e:ex2_yes},
		{c:"No",e:ex2_no}
	]
);

function ex2_yes(){
	alert("Yes")
}

function ex2_no(){
	alert("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){
	alert(d)
}

function ex4_opt2(d){
	alert(d)
}

function ex4_opt3(d){
	alert(d)
}



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

Page 1 of 1