ARTICLE :
 

Cross-browser Modal Popup using Javascript (JQuery)

by SBajra on April 20th, 2011

Introduction

This article is to create simple cross-browser modal popup using Javascript (JQuery) and HTML only. No external complex code is required. This would be the most simplest but yet fully compatible implementation of Modal popup window for web application. It utilizes JQuery for its implementation. JQuery is open-source Javascript framework with cross-browser support. This modal popup works in most of the popular browsers that supports JQuery including IE6+, FireFox, Chrome, Safari, Opera etc.

Background

Web application is getting more and more dynamic, complex and rich in UI. There are lots of instances where we would need a modal popup for displaying messages, displaying dialog box, displaying survey etc.

Some of the traditional techniques for popup windows are by using Javascript function such as window.location.href (URL) or, by setting target="_blank" to a link <a target="_blank" >click here</a>. But these techniques have some disadvantages such as it loads whole new page in the popup window, popup windows could be blocked by many browsers and it's outside of the scope of current window. Due to these issues, web trend is moving more and more towards using modal popup.

I always think if there is an easier solution to build these modal popup for the websites. I tried Microsoft AJAX Modal Popup extender, JQuery plugins etc. It works but it adds lot of Javascript code as well and I always wanted to implement my own simple version of modal popup that works with all the browsers. So, I came up with this simple code to create fully cross-browser compatible modal popup using Javascript and JQuery. Why I chose JQuery is because it already does lot of cross-browser validation.

Detail

The simple concept behind modal popup window is that, you have to display modal popup content in the center of the page with rest of the page disabled. So, first thing we need to do is to define the modal popup content area.

Sample modal popup content area:

  <div id="dvPopup"  style="display:none; width:400px; height: 200px; border:4px solid #000000; background-color:#FFFFFF;">
    This is popup window. Popup content goes  here.
  </div>

Popup window is defined by using <div> tags with appropriate styles and display:none. It is important to hide the popup window initially using display:none style. You can add whatever style or content to this popup content area. You have full control over the modal popup content area.

Then we need to write some code to trigger this modal popup. Triggering modal popup simply means making the popup content section visible at the center of the page with background disabled.

Modal popup content could be displayed by clicking a button or a link or using any event.
In this example, I am triggering modal popup content area using a HTML link.

HTML code to trigger modal popup content:
<a href="#" onclick="ShowModalPopup('dvPopup'); return false;">Click here</a>

Since we are using JQuery to implement this modal popup, we need to include the JQuery library. You can download JQuery library from JQuery.com or link to external CDN (Content Delivery Network) hosted sites.

Including JQuery javascript library:
<script language="javascript" type="text/javascript" src="/jquery/1.5.2/jquery.min.js"></script>

Javascript code to show the modal popup:

//Modal popup background ID. This is global scope and 
//This value should be unique so that it does not conflict with other IDs in the page.
var _ModalPopupBackgroundID = 'backgroundPopup_XYZ_20110418_Custom';

function ShowModalPopup(modalPopupID) {

    //Setting modal popup window

    //Boolean to detect IE6.
    var isIE6 = (navigator.appVersion.toLowerCase().indexOf('msie 6') > 0);

    var popupID = "#" + modalPopupID;

    //Get popup window margin top and left
    var popupMarginTop = $(popupID).height() / 2;
    var popupMarginLeft = $(popupID).width() / 2;

    //Set popup window left and z-index
    //z-index of modal popup window should be higher than z-index of modal background
    $(popupID).css({
        'left': '50%',
        'z-index': 9999
    });

    //Special case for IE6 because it does not understand position: fixed
    if (isIE6) {
        $(popupID).css({
            'top': $(document).scrollTop(),
            'margin-top': $(window).height() / 2 - popupMarginTop,
            'margin-left': -popupMarginLeft,
            'display': 'block',
            'position': 'absolute'
        });
    }
    else {
        $(popupID).css({
            'top': '50%',
            'margin-top': -popupMarginTop,
            'margin-left': -popupMarginLeft,
            'display': 'block',
            'position': 'fixed'
        });
    }

    //Automatically adding modal background to the page.
    var backgroundSelector = $('<div id="' + _ModalPopupBackgroundID + '" ></div>');

    //Add modal background to the body of the page.
    backgroundSelector.appendTo('body');

    //Set CSS for modal background. Set z-index of background lower than popup window.
    backgroundSelector.css({
        'width': $(document).width(),
        'height': $(document).height(),
        'display': 'none',
        'background-color': '#555555',
        'position': 'absolute',
        'top': 0,
        'left': 0,
        'z-index': 9990
    });

    backgroundSelector.fadeTo('fast', 0.8);
}

  

The Javascript code above is using JQuery for some of the functionality and technically displaying the popup content area in the center of the screen. This code also attaches semi-transparent background to hide the main page content. The trick is, z-index of popup content area is set to high value like 9999 and z-index for background is set to 9990 so that popup content area appears on top of everything and semi-transparent background hides the entire page content. Also apply position:fixed style to the popup content area so that it is fixed regardless of page scrolling.

However, there is a catch with Internet Explorer 6 (IE6). IE6 does not support position:fixed style. So, need to apply position:absolute style specially for IE6. This will pop up the modal content area using absolute positioning. But by default, it won't be fixed to the screen, which means if you move scrollbars then popup content area will move as well. To solve this issue, we need to add IE6 specific patch using CSS.

CSS patch for IE6 (optional):

  <style>
    *html #dvPopup
        {
        	top:expression(eval(document.documentElement.scrollTop)) !important;
        }
  </style>
  

Fortunately, only IE6 understand *html style convention and also understands use of expression. This piece of code will fix the modal popup content area to the center of the page for IE6 regardless of scrolling.

Now, once the modal popup is displayed, to close the modal popup content window we need to write small Javascript again.

Javascript code to hide the modal popup content:

function HideModalPopup(modalPopupID) {
    //Hide modal popup window
    $("#" + modalPopupID).css('display', 'none');

    //Remove modal background from DOM.
    $("#" + _ModalPopupBackgroundID).remove();
}

The Javascript code above will technically hide the modal popup content area and remove the semi-transparent background from DOM.

That's it. Now you have a fully cross-browser compatible and highly customization modal popup implementation of your own.

Click here to view the demo

Conclusion

It is quite easy to create simple but yet highly customizable and powerful cross-browser compatible modal popup window using few lines of Javascript and JQuery.

Download

Click here to download source code

Author:

Profile Photo
SBajra
Date: April 20th, 2011

Comments:



Profile Photo
Commented by Sunil Sharma
on May 21st, 2011 at 09:56:32 EST
Nice article. Thanks.

Profile Photo
Commented by Arpit Raj
on February 24th, 2012 at 02:34:37 EST
Thanks for the article.

I am designing a page where I intend to use multiple popups and I have a few questions.
1. Every popup will have different contents, hence, width and height of the popup should be according to the content and the popup should still be in the middle of the screen horizontally and vertically.
2. If the content is too long then the height of the popup needs to be fixed to like 60% of the screen, and the div should have a scroll bar to see remaining content.

Could you provide the modified code for these points.

Profile Photo
Commented by Somesh N
on May 17th, 2012 at 10:58:49 EST
How can we make this modal popup resizable and draggable. Please give me a solution ASAP.