Paulund
2011-09-24 #jquery

How To Create A Simple Modal Box With JQuery

There are loads of plugins out there to use for a modal box but some of over complicated for this simple task of showing a message on the screen in a lightbox. I decided that I would build my own and in this tutorial I will show you how to build a simple modal box in jquery.

What Were Working Towards

We are going to build a jquery plugin that on click of a link will black out the rest of the screen and display a lightbox with a custom message inside and a close button to remove the modal box. I want to keep all the work of creating the box and the styling inside the plugin so we don't have to do anything else apart from include the plugin in the document. Normally with other plugins you have to make up the box yourself and the jquery plugin will just display it, I want the plugin to make and style the modal box. This will make it so much easier to add into the HTML and quickly display a modal box. Now lets begin.

The HTML

As I said above I want to keep the HTML and CSS to a minimum and let the plugin do the work for you, therefore the HTML is very simple. We want this run on the click event of a link, so we need to create a link and add a class so we can reference it later.


<a href="#" class="paulund_modal">Click Here</a>

That's it. There is no CSS so now we can get straight to creating the JQuery plugin.

Create The JQuery Modal Box Plugin

First lets start with the basic structure of creating a jQuery Plugin. Create a new javascript file and call it jquery.paulund_modal_box.js and save in the same folder as your webpage.


(function($){

	// Defining our jQuery plugin
	$.fn.paulund_modal_box = function(prop){

		// Default parameters

		var options = $.extend({
			height : "250",
			width : "500",
			title:"JQuery Modal Box Demo",
			description: "Example of how to create a modal box.",
			top: "20%",
			left: "30%",
		},prop);
				
		return this.click(function(e){
		     //Do stuff here
		});
				 		
		return this;
	};
	
})(jQuery);

The above is the basic structure for JQuery plugin it will create a plugin called paulund_modal_box and on the click event of the element will do something. I have also put in a number of different default parameters we can use to construct our box. I have put these as parameters so we can change them later on. Now in the click event we are going to create the modal box. As we didnt include any HTML or CSS on the page we need to do a number of different tasks:

  1. Block out the rest of the screen so we can only see the modal box.
  2. Create the modal box HTML.
  3. Style the two new elements.
  4. Finally when all this is done we need to display the modal box

We need these functions into the the click event.

return this.click(function(e){
	add_block_page();
	add_popup_box();
	add_styles();
			
	$('.paulund_modal_box').fadeIn();
});

Now we have the structure of the functions we want to use lets add the functionality to this functions.

Add Block Page

This is going to be the blacked out div which will stop the user accessing other areas of the page while the modal box in on screen. It is simply a div which will cover the whole screen and we will put the modal box inside this div. Create the function add_block_page(), which creates a div and adds it to the body tag in the HTML.

function add_block_page(){
	var block_page = $('<div class="paulund_block_page"></div>');
						
	$(block_page).appendTo('body');
}

We want to make this box take up the whole screen and block out the screen so lets add the styles to the styling function.

function add_styles(){			
        /*Block page overlay*/
	var pageHeight = $(document).height();
	var pageWidth = $(window).width();

	$('.paulund_block_page').css({
		'position':'absolute',
		'top':'0',
		'left':'0',
		'background-color':'rgba(0,0,0,0.6)',
		'height':pageHeight,
		'width':pageWidth,
		'z-index':'10'
	});
}

The screen is now blocked from this div so we can now add the modal box in.

Create Modal Box

To create the modal box we are using the function add_popup_box().


function add_popup_box(){
	 var pop_up = $('<div class="paulund_modal_box"><a href="#" class="paulund_modal_close"></a><div class="paulund_inner_modal_box"><h2>' + options.title + '</h2><p>' + options.description + '</p></div></div>');
	$(pop_up).appendTo('.paulund_block_page');
			 			 
	$('.paulund_modal_close').click(function(){
            $('.paulund_block_page').fadeOut().remove();		
            $(this).parent().fadeOut().remove();					 
	});
}

This creates a div which has a title, description and a link to close the box. It will then append the modal box to the blocked out div and creates a click event on the close box to remove the modal box. Like above we need to add the styles for the modal box so add the following into the add_styles function we created above.


         $('.paulund_modal_box').css({ 
		'position':'absolute', 
		'left':options.left,
		'top':options.top,
		'display':'none',
		'height': options.height + 'px',
		'width': options.width + 'px',
		'border':'1px solid #fff',
		'box-shadow': '0px 2px 7px #292929',
		'-moz-box-shadow': '0px 2px 7px #292929',
		'-webkit-box-shadow': '0px 2px 7px #292929',
		'border-radius':'10px',
		'-moz-border-radius':'10px',
		'-webkit-border-radius':'10px',
		'background': '#f2f2f2', 
		'z-index':'50',
	});
	$('.paulund_modal_close').css({
		'position':'relative',
		'top':'-25px',
		'left':'20px',
		'float':'right',
		'display':'block',
		'height':'50px',
		'width':'50px',
		'background': 'url(images/close.png) no-repeat',
	});
	$('.paulund_inner_modal_box').css({
		'background-color':'#fff',
		'height':(options.height - 50) + 'px',
		'width':(options.width - 50) + 'px',
		'padding':'10px',
		'margin':'15px',
		'border-radius':'10px',
		'-moz-border-radius':'10px',
	        '-webkit-border-radius':'10px'
	});

That's it your JQuery plugin is now finished.

The Final JQuery Plugin

Incase you missed a step here is the finished JQuery Plugin.


(function($){

	// Defining our jQuery plugin

	$.fn.paulund_modal_box = function(prop){

		// Default parameters

		var options = $.extend({
			height : "250",
			width : "500",
			title:"JQuery Modal Box Demo",
			description: "Example of how to create a modal box.",
			top: "20%",
			left: "30%",
		},prop);
				
		return this.click(function(e){
			add_block_page();
			add_popup_box();
			add_styles();
			
			$('.paulund_modal_box').fadeIn();
		});
		
		 function add_styles(){			
			$('.paulund_modal_box').css({ 
				'position':'absolute', 
				'left':options.left,
				'top':options.top,
				'display':'none',
				'height': options.height + 'px',
				'width': options.width + 'px',
				'border':'1px solid #fff',
				'box-shadow': '0px 2px 7px #292929',
				'-moz-box-shadow': '0px 2px 7px #292929',
				'-webkit-box-shadow': '0px 2px 7px #292929',
				'border-radius':'10px',
				'-moz-border-radius':'10px',
				'-webkit-border-radius':'10px',
				'background': '#f2f2f2', 
				'z-index':'50',
			});
			$('.paulund_modal_close').css({
				'position':'relative',
				'top':'-25px',
				'left':'20px',
				'float':'right',
				'display':'block',
				'height':'50px',
				'width':'50px',
				'background': 'url(images/close.png) no-repeat',
			});
                        /*Block page overlay*/
			var pageHeight = $(document).height();
			var pageWidth = $(window).width();

			$('.paulund_block_page').css({
				'position':'absolute',
				'top':'0',
				'left':'0',
				'background-color':'rgba(0,0,0,0.6)',
				'height':pageHeight,
				'width':pageWidth,
				'z-index':'10'
			});
			$('.paulund_inner_modal_box').css({
				'background-color':'#fff',
				'height':(options.height - 50) + 'px',
				'width':(options.width - 50) + 'px',
				'padding':'10px',
				'margin':'15px',
				'border-radius':'10px',
				'-moz-border-radius':'10px',
				'-webkit-border-radius':'10px'
			});
		}
		
		 function add_block_page(){
			var block_page = $('<div class="paulund_block_page"></div>');
						
			$(block_page).appendTo('body');
		}
		 		
		 function add_popup_box(){
			 var pop_up = $('<div class="paulund_modal_box"><a href="#" class="paulund_modal_close"></a><div class="paulund_inner_modal_box"><h2>' + options.title + '</h2><p>' + options.description + '</p></div></div>');
			 $(pop_up).appendTo('.paulund_block_page');
			 			 
			 $('.paulund_modal_close').click(function(){
				$(this).parent().fadeOut().remove();
				$('.paulund_block_page').fadeOut().remove();				 
			 });
		}

		return this;
	};
	
})(jQuery);

Using The JQuery Plugin

We have created the plugin now how do we use it? Go back to your HTML and make sure you include JQuery and your plugin in your head tag.


<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
<script src="jquery.paulund_modal_box.js"></script>

The plugin is now included on the page so we can assign it to a link and call the modal box on the click event. Create a script tag just above the closing body tag and add the following.


<script>
$(document).ready(function(){
	$('.paulund_modal').paulund_modal_box();
});
</script>

Now when you click on the link you will see the modal box from the plugin, if you create multiple links with the class .paulund_modal each time you click on these links you will see your modal box.

Using the Parameters

At the start of the tutorial I spoke about the default parameters which are using to construct the modal box. Now we can use these to change the text inside the modal box or the size of the box. Below is how you can change the parameter to suit your needs.

<script>
$(document).ready(function(){
	$('.paulund_modal').paulund_modal_box();
	$('.paulund_modal_2').paulund_modal_box({
		title:'Second Title Box',
		description:'Custom description for box <br/><br/>Quisque sodales odio nec dolor porta sed laoreet mauris pretium. Aenean id mauris ligula, semper pulvinar dolor. Suspendisse rutrum, libero eu condimentum porta, mauris mauris semper augue, ut tempor nunc arcu vel ligula. Quisque orci eros, consequat vel iaculis eget, blandit bibendum est. Morbi ac tellus dui. Nullam eget eros et lectus dignissim placerat. Nulla facilisi. Ut congue posuere vulputate.'
	});
	$('.paulund_modal_3').paulund_modal_box({
		title: 'Change Title with height',
		height: '500'
	});
	$('.paulund_modal_4').paulund_modal_box({
		title: 'Change Title with Width',
		width: '800'
	});
	$('.paulund_modal_5').paulund_modal_box({
		title:'Second Title Box',
		description:'Custom description for box <br/><br/>Quisque sodales odio nec dolor porta sed laoreet mauris pretium. Aenean id mauris ligula, semper pulvinar dolor. Suspendisse rutrum, libero eu condimentum porta, mauris mauris semper augue, ut tempor nunc arcu vel ligula. Quisque orci eros, consequat vel iaculis eget, blandit bibendum est. Morbi ac tellus dui. Nullam eget eros et lectus dignissim placerat. Nulla facilisi. Ut congue posuere vulputate.',
		height: '500',
		width: '800'
	});
});
</script>

UpChecker

Reliable uptime monitoring and instant alerts for any website downtime.

  • Uptime Monitoring
  • Performance Monitoring
  • SSL Certificate Alerts
  • Domain Monitoring
  • DNS Checker
  • XML Sitemap Monitoring