Click here to Skip to main content
15,891,253 members
Articles / Web Development / HTML

JavaScript Modal Popup Window

Rate me:
Please Sign up or sign in to vote.
4.84/5 (48 votes)
15 May 2014CPOL3 min read 696.7K   39.5K   55   136
Flexible JavaScript Modal Popup Window
Image 1

Introduction

Nowadays, JavaScript Modal Popup window has become an intrinsic part of Web based application. Lately, I had a requirement where I needed to use Modal Popup Window. I Goggled for it and found many JQuery based Modal Popup Windows, but none of the code was fitting my needs.

So I decided to create my own Modal Popup window without using JQuery which should be easy to use and is flexible.

Using the Code

First, you need include ModalPopupWindow.js file in your web page as given below:

JavaScript
<script src="JavaScript/ModalPopupWindow.js"
type="text/javascript"></script>

Once you have included the JS file, you need to create an instance of ModalPopUpWindow. For that, you need to write the below mentioned code:

JavaScript
modalWin = new CreateModalPopUpObject();

modalWin object provides three functions to create three types of modal windows which are mentioned below:

  • ShowMessage
  • ShowConfirmationMessage
  • ShowURL

ShowMessage

ShowMessage can be used when you want to show some information to the user:

Image 2

JavaScript
ShowMessage(message, height, width, title)

ShowMessage function takes four parameters:

  • Message: Message that you need to display to the user
  • Height: Height of the message window
  • Width: Width of message window
  • Title: Title of the window

Syntax for calling is as follows:

JavaScript
modalWin.ShowMessage('This Modal Popup Window using Javascript',200,400,'User Information');

ShowConfirmationMessage

ShowConfirmationMessage window can be used where you want to take confirmation from user:

Image 3

JavaScript
ShowConfirmationMessage(message, height,
            width, title, onCloseCallBack, firstButtonText, onFirstButtonClick, secondButtonText,
            onSecondButtonClick)

ShowConfirmationMessage function takes eight parameters:

message, height, width, title parameters are already described above.

  • onCloseCallBack (optional): Name of the function that will get called on confirmation window close
  • firstButtonText: Text that needs to be displayed on first button (like Yes, Agree, OK, etc.)
  • onFirstButtonClick: Name of the function that will get called on click of first button.
  • secondButtonText: Text that needs to be displayed on second button (like Yes, Agree, OK, etc.)
  • onSecondButtonClick: Name of the function that will get called on click of second button

Syntax for calling is as given below:

JavaScript
modalWin.ShowConfirmationMessage('This
           Modal Popup Window using Javascript',200,400,'User Confirmation',
           null,'Agree',Action1,'Disagree',Action2);

ShowURL

ShowURL function can be used when you want to display a new page or URL in Modal popup window.

Image 4

JavaScript
ShowURL(url, height, width, title,
           onCloseCallBack, callbackFunctionArray)

height, width, title, onCloseCallBack are already described above.

  • url: Location or URL of the web page
  • callbackFunctionArray (optional): Using this parameter, you can pass array of function of parent page to the child page inside Modal Window. So that child page can access function of parent page.

Syntax for calling is as follows:

JavaScript
var callbackFunctionArray = new Array(EnrollNow,
EnrollLater);

modalWin.ShowURL('Child.htm',320,470,'User
Enrollment',null,callbackFunctionArray);   

SetButtonStyle

You can change the button style using function SetButtonStyle. Sometimes, you may want to show button as link, in that case you can use this function. Below is an example to show buttons as link.

Image 5

JavaScript
SetButtonStyle(btnStyle)
  • btnStyle: is semicolon separated styles for buttons. The naming convention for the styles should be like JavaScript not like CSS style. For example in CSS, we use "text-decoration" and in JavaScript, we use "textDecoration". So, please make sure while passing styles that you are using JavaScript naming convention.

Syntax for calling is as given below:

JavaScript
modalWin.SetButtonStyle("background:none;border:none;textDecoration:underline;cursor:pointer");

Dragging Window

By default ModalPopUpWindow is draggable, for dragging window you need press mouse over window title bar and drag. In case you don’t want window to be draggable, then you can use Draggable property of ModalPopUpWindow. You need to set this property every time just before calling any show function of ModalPopUpWindow to make it un-draggable

Image 6

Syntax for making window un-draggable is given below:

JavaScript
modalWin.Draggable=false;
modalWin.ShowMessage('You can not drag this window',200,400,'User Information');

Passing Values From Modal Popup Child Window To Parent Window

Sometimes, we may need to pass values from child modal window to parent window while using "ShowURL" function of modal window. In JavaScript, we can use window.parent for accessing parent window elements/functions. So we can use the same (window.parent) for passing value from child popup window to parent window. You can find example of the same in the attached demo code where clicking on "Show URL Window" will show up popup window and when you will click on "Enroll Now" button, it will pass values of child window to parent window as shown in below screenshots:

Image 7

Image 8

Summary

In the attached source code, you will find examples for all the scenarios described in this tip. Apart from that, you can modify the source code depending on your requirement.

History

  • Updated source code version v4 for supporting IE11 on 20-Nov-2013

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
Developer

Comments and Discussions

 
QuestionHow to get true or false on press Agree in confirmation window Pin
nishhu0717-Oct-14 2:44
nishhu0717-Oct-14 2:44 
AnswerRe: How to get true or false on press Agree in confirmation window Pin
Mahesh Bailwal18-Oct-14 6:04
Mahesh Bailwal18-Oct-14 6:04 
GeneralRe: How to get true or false on press Agree in confirmation window Pin
nishhu0731-Oct-14 3:08
nishhu0731-Oct-14 3:08 
QuestionShow URL window cannot close by itself? Pin
Member 111299415-Oct-14 14:09
Member 111299415-Oct-14 14:09 
AnswerRe: Show URL window cannot close by itself? Pin
Mahesh Bailwal6-Oct-14 8:28
Mahesh Bailwal6-Oct-14 8:28 
GeneralRe: Show URL window cannot close by itself? Pin
Member 111299416-Oct-14 9:34
Member 111299416-Oct-14 9:34 
GeneralRe: Show URL window cannot close by itself? Pin
Mahesh Bailwal7-Oct-14 7:40
Mahesh Bailwal7-Oct-14 7:40 
GeneralRe: Show URL window cannot close by itself? Pin
Member 111299417-Oct-14 9:17
Member 111299417-Oct-14 9:17 
Hi Mahesh, thanks for you help. I am ready to pull my hair out on this already. It's very frustrating. Here is the main structure of the calling program proposal.htm with the javascript called etc. It's done in Coldfusion.

XML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Send Proposal</title>
<meta name="description" content="Send proposal">

<link href="css/form.css" media="screen" rel="stylesheet" type="text/css" />
<link href="css/style.css" media="screen" rel="stylesheet" type="text/css" />
<link href="css/default.css" media="screen" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="js/jquery/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="js/tabmenu.js"></script>
<script type="text/javascript">
tabmenu.definemenu("tabs", 0)
tabmenu.definemenu("tabs2", 0)
</script>
<!--[if lt IE 7]>
<script type="text/javascript" src="js/jquery/jquery.js"></script>
<script type="text/javascript" src="js/jquery/jquery.dropdown.js"></script>
<![endif]-->
</head>
<body>
<div class="main">
<script type="text/javascript" src="js/ModalPopupWindow.js"></script>
<cfif not isdefined("p1")>
    <div class="padleft15">
    <cfset reckey = generateSecretKey("desede")>
    <cfset listid = encrypt(f1, reckey, "desede", "base64")>
    <cfcookie name="fto_r" value="#reckey#">

    <cfform action="proposal.htm" method="post">
    <cfoutput>
    <input type="hidden" name="f1" value="#f1#">
    <input type="hidden" name="p1" value="#listid#">
    <input type="hidden" name="mt" value="#mt#">
    <input type="hidden" name="contact" value="#contact#">
    <input type="hidden" name="company" value="#company#">
    <legend><h3>Contact Buyer</h3></legend>
    <p class="padtop15">
    <label for="email" class="f75">From: </label>
    <cfif isdefined("cookie.fto_e")>
        <cfset useremail = decrypt(cookie.fto_e, "62Luv4VWQpw")>
    <input type="hidden" name="email" value="#useremail#">#useremail#
    <cfelse>
        <cfinput type="text" class="f280" name="email" placeholder="Enter email" size="50" maxlength="50" required="yes" autofocus="on" validate="email" message="You must enter a valid e-mail address.">
    </cfif>
    <p><label for="to" class="f75">To: </label>
    <b>#contact#</b> (#company#)
    </cfoutput>
    <p><label for="subject" class="f75">Subject: </label>
    <cfinput type="text" class="f280" name="subject" placeholder="Enter subject" size="50" maxlength="50" required="yes" value="#subject#" validate="noblanks" message="You must enter a subject.">
    <p><label for="message" class="f75">Message: </label>
    <cftextarea name="message" cols="45" rows="8" wrap="soft" required="yes" validate="noblanks" message="Please enter a message for your offer."></cftextarea>
    <p class="padleft110">
    <input type="submit" value=" Send "> &nbsp;
    <input type="reset" value=" Reset ">
    </cfform>
    </div>
<cfelse>
    <cfif isdefined("cookie.ftouser") and isdefined("cookie.fto_a") and isdefined("cookie.fto_r") and isdefined("cookie.fto_u") and isdefined("cookie.fto_n") and isdefined("cookie.fto_e") and isdefined("cookie.fto_c")>
        ...user is signed in....
    <cfelse>
        <script type='text/javascript'>
            modalWin = new CreateModalPopUpObject();
            modalWin.SetLoadingImagePath("images/loading.gif");
            modalWin.SetCloseButtonImagePath("images/remove.gif");
            var callbackFunctionArray = new Array(HideModalWindow);
            modalWin.ShowURL("https://mydomain/login.htm", 280, 350, "Sign In",HideModalWindow,callbackFunctionArray);
            function HideModalWindow() {
                modalWin.HideModalPopUp();
            }
        </script>
        <div class="padleft15">
        <cfform action="proposal.htm" method="post">
        <cfoutput>
        <input type="hidden" name="f1" value="#f1#">
        <input type="hidden" name="p1" value="#p1#">
        <input type="hidden" name="mt" value="#mt#">
        <input type="hidden" name="contact" value="#contact#">
        <input type="hidden" name="company" value="#company#">
        <legend><h3>Contact</h3></legend>
        <p class="padtop15">
        <label for="email" class="f75">From: </label>
        <cfinput type="text" class="f280" name="email" placeholder="Enter email" size="50" maxlength="50" required="yes" autofocus="on" value=#HTMLEditFormat(email)#  validate="email" message="You must enter a valid e-mail address.">
        <p><label for="to" class="f75">To: </label>
        <b>#contact#</b> (#company#)
        <p><label for="subject" class="f75">Subject: </label>
        <cfinput type="text" class="f280" name="subject" placeholder="Enter subject" size="50" maxlength="50" required="yes" value="#subject#" validate="noblanks" message="You must enter a subject.">
        <p><label for="message" class="f75">Message: </label>
        <cftextarea name="message" cols="45" rows="8" wrap="soft" required="yes" validate="noblanks" message="Please enter a message for your offer.">#message#</cftextarea>
        </cfoutput>
        <p class="padleft110">
        <input type="submit" value=" Send "> &nbsp;
        <input type="reset" value=" Reset ">
        </cfform>
        </div>
    </cfif>
</cfif>
</div>
</body>
</html>


The ModalPopupWindow javascript is called later because the others were in templates. The main structure of the called login.htm is as follows:


XML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Sign In</title>
<link href="css/form.css" media="screen" rel="stylesheet" type="text/css" />
<style>
body {
font: 12px/normal arial, Helvetica, sans-serif;
}
.pad100{padding-left:100px;}
.padtop5{
    padding-top:5px;
}
.warning{color:red;font-weight:bold;text-align:center;}
</style>
</head>
<body>
<cfset message="">
<cfif not isdefined("cookie.cookietest")>
    <cfcookie name="cookietest" value="y">
</cfif>
<cfif not isdefined("cookie.cookietest")>
    <cfset message="Your browser is not accepting cookies!">
</cfif>
<cfif not isdefined("userid") or not isdefined("password")>
    <cfset userid="">
    <cfset password="">
<cfelse>

    ... check user input ...
    <cfif #checklist.recordcount# equal 0>
        <cfset message="Invalid Member ID or Password!">
    <cfelse>
        ...id and pw validated, set cookies and close pop up...
        <script type='text/javascript'>
        window.document.forms[0].submit();
        window.parent.HideModalWindow();
        </script>
        </body>
        </html>
        <cfabort>
    </cfif>

</cfif>

<cfform action="login.htm" method="post">
<cfoutput>
<div class="padtop5">
<p><label for="userid" class="f75">Member ID: </label> <cfinput class="f200" name="userid" value="#userid#" autofocus="on" required="yes" maxlength="20" type="text" validate="noblanks" message="Please enter your Member ID."></p>
<p><label for="password" class="f75">Password: </label> <cfinput class="f200" name="password" required="yes" maxlength="20" type="password" validate="noblanks" message="Please enter your password."></p>
<p class="pad100"><a target="_blank" href="forgot.htm">Forgot your ID / password?</a>
<p class="submit"><input type="submit" value=" Sign In "></p>
<p class="pad100">Not yet a member? <a target="_blank" href="register.htm">Join Free</a></p>
<p class="warning">#message#</p>
</div>
</cfoutput>
</cfform>
</body>
</html>



I hope you can see what is wrong. Is it possible that the close function
window.parent.HideModalWindow();

does not know what it suppose to close? That's the only reason I can think of that it cannot find the popup window to close it and submit the form. But one thing I notice that even the submit form is not submit for some reason. It is the right format for submitting the parent form (I tested and it worked before). Now it's not submitting nor closing the popup. Frown | :(

Note: the proposal.htm is on http and login.htm is on https, but I have set Access-Control-Allow-Origin for the https domain. I also did put both on http and it still won't close.

modified 7-Oct-14 17:44pm.

GeneralRe: Show URL window cannot close by itself? Pin
Mahesh Bailwal10-Oct-14 22:08
Mahesh Bailwal10-Oct-14 22:08 
QuestionPopup Is Not Modal and Page is Cleared by ShowConfirmationMessage Pin
CdlBob10-Sep-14 12:48
CdlBob10-Sep-14 12:48 
AnswerRe: Popup Is Not Modal and Page is Cleared by ShowConfirmationMessage Pin
Mahesh Bailwal11-Sep-14 2:49
Mahesh Bailwal11-Sep-14 2:49 
GeneralRe: Popup Is Not Modal and Page is Cleared by ShowConfirmationMessage Pin
jeetendra keshri116-Sep-15 7:01
jeetendra keshri116-Sep-15 7:01 
Questionclose button Pin
Megan Ramarama3-Sep-14 21:07
Megan Ramarama3-Sep-14 21:07 
QuestionResizable Property Pin
akhtar.shahbaz120-Aug-14 3:36
professionalakhtar.shahbaz120-Aug-14 3:36 
AnswerRe: Resizable Property Pin
Mahesh Bailwal21-Aug-14 18:23
Mahesh Bailwal21-Aug-14 18:23 
GeneralRe: Resizable Property Pin
akhtar.shahbaz121-Aug-14 21:34
professionalakhtar.shahbaz121-Aug-14 21:34 
GeneralRe: Resizable Property Pin
Mahesh Bailwal23-Aug-14 20:37
Mahesh Bailwal23-Aug-14 20:37 
GeneralRe: Resizable Property Pin
akhtar.shahbaz11-Sep-14 20:03
professionalakhtar.shahbaz11-Sep-14 20:03 
GeneralLimitations Pin
Member 1101348014-Aug-14 14:11
Member 1101348014-Aug-14 14:11 
GeneralRe: Limitations Pin
Mahesh Bailwal14-Aug-14 20:47
Mahesh Bailwal14-Aug-14 20:47 
QuestionI am searching where is blank.htm ..in the script it is there... Pin
vic533-Aug-14 10:41
professionalvic533-Aug-14 10:41 
AnswerRe: I am searching where is blank.htm ..in the script it is there... Pin
Mahesh Bailwal4-Aug-14 3:43
Mahesh Bailwal4-Aug-14 3:43 
QuestionSuperb!!! Pin
Ashutosh Phoujdar25-Jul-14 22:38
Ashutosh Phoujdar25-Jul-14 22:38 
AnswerRe: Superb!!! Pin
Mahesh Bailwal26-Jul-14 23:10
Mahesh Bailwal26-Jul-14 23:10 
Questionparamter from parent to child Pin
Mansouri Mohamed23-Jul-14 4:10
Mansouri Mohamed23-Jul-14 4:10 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.