jQuery message box

27.Dec.2010

Many times there is a need for showing message to a user. If you would like to show your user modal window message, try following – jQuery message box.

Before we start – you can take a look at the demo message – made just for you! Click here…

In order to show jQuery message box – we first need to setup a CSS for both message and background. Copy following CSS into your CSS file in order to set style.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#darkbg {
	display: none;
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background: #000;

	opacity: .5;
	filter: alpha(opacity=50);
	-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";
}
#message_box {
	width: 300px;
	height: 150px;
	background: #fff;

	border: 4px solid #f0f0f0;
	border-radius: 10px;
	-moz-border-radius: 10px;
	-webkit-border-radius: 10px;
 
	position: fixed;
	top: 100px;
	left: 50%;
	margin-left: -150px;
 
	text-align: center;
	z-index: 1000;
	display: none;
}
#message_box input[type=button] {
	float: right;
	margin-right: 10px;
}

Now that we have CSS setup, it is time to write some JavaScript code. This JavaScript code is heart and soul of this jQuery message box. So, copy next lines into your .js file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
var message_box = function() {
	var button = '<input type="button" onclick="message_box.close_message();" value="Okay!" />';
	return {
		show_message: function(title, body) {
			if(jQuery('#message_box').html() === null) {
				var message = '<div id="message_box"><h1>' + title + '</h1>' + body + '<br/>' + button + '</div>';
				jQuery(document.body).append( message );
				jQuery(document.body).append( '<div id="darkbg"></div>' );
				jQuery('#darkbg').show();
				jQuery('#darkbg').css('height', jQuery(document).height());
 
				jQuery('#message_box').css('top', 150);
				jQuery('#message_box').show('slow');
			} else {
				var message = '<h1>' + title + '</h1>' + body + '<br/>' + button;
				jQuery('#darkbg').show();
				jQuery('#darkbg').css('height', jQuery(document).height());
 
				jQuery('#message_box').css('top', 150);
				jQuery('#message_box').show('slow');
				jQuery('#message_box').html( message );
			}
		},
		close_message: function() {
			jQuery('#message_box').hide('fast');
			jQuery('#darkbg').hide();
		}
	}
}();

Now, we are almost done, we just need to be able to init message showing from our jQuery message box. This can be done in simple JavaScript function call:

message_box.show_message('Hi!', 'Whatup?!');

You can bind it to onclick event as well:

1
2
3
jQuery('#some_link').onclick(function() {
    message_box.show_message('Hi!', 'Whatup?!');
});

Example of jQuery message box

Click me – click me!