Modal Dialog

Modal Dialog 


this article can be considered as a follow up to my former
Modeling a Draggable Layer and Loading Dynamic Content to it via XML HTTP
article. Have a look at it, if you have not done already so that you can catch up faster.
 
Introduction
this article can be considered as a follow up to my former
Modeling a Draggable Layer and Loading Dynamic Content to it via XML HTTP
article. Have a look at it, if you have not done already so that you can catch up faster. 
in this article, we will try to 

Create a cross-browser, draggable DHTML Modal Dialog
Send an AJAX request using HTTP-POST.
Get the response and display it inside the modal dialog
and best of all, we will do all these in less than 20 lines of code,  with the help of
sardalya
API.

Please note that the API enclosed in this article's source archive is a rather simplified version of sardalya. You can visit
sardalya's web site
for the latest full version of it. 
before starting, you may want to
see the final result it in action
first.
 


 
Creating the View
the HTML of our ModalDialog is fairly simpe: 
<div id="ModalBG"></div>

<div id="DialogWindow">
  <div id="DialogHeader">
    Title comes here
    <img id="DialogActionBtn"  src="http://www.aspxboy.com/private/5385/icn_close.png" alt="close icon" title="" />
  </div>
  <div id="DialogIcon"><img id="DialogIcon" src="http://www.aspxboy.com/private/5385/icn_alert.png" alt="alert icon" title="" /></div>
  <div id="DialogContent">...</div>
</div> "ModalBG" is a layer that is placed between the page content and the ModalDialog window so that we prevent accidential clicks on other page elements and in the same time put some visual emphasis on the ModalDialog by fading the page in the background.
The CSS
to make our "DialogWindow" layer resemble an actual modal dialog, we need some CSS tweaks:  Master.css

#DialogWindow
{
border: 1px #FFFFFF outset;
width: 550px;
display: none;
background: #FFFFFF;
z-index: 1000;
position: absolute;
top: 0;
left: 0;
}

#DialogContent
{
float: right;
margin-right: 10px;
margin-bottom: 10px;
margin-top: 24px;
width: 450px;
display: block;
font-size: 90%;
}


#DialogIcon
{
padding: 10px;
float: left;
}

#DialogHeader
{
border-bottom: 1px #00449E outset;
background: #00449E;
text-align: right;
}

#DialogTitle
{
float: left;
padding: 8px;
color: #FFFFFF;
}

#DialogActionBtn
{
cursor:pointer;
}

and we need an "Opacity.css" for transparency support:  Opacity.css

#ModalBG
{
width:100%;
display:none;
background-color:#333333;
position:absolute;
top:0;
left:0;
height:100%;
z-index:999;
opacity:.40;
filter:alpha(opacity=40)
}
with the help of this CSS, our boxes will pretty much look like a Modal Dialog, except for certain browsers: 
Be Kind to Opera
i hear you say "Why am I to be kind to Opera all the time? why is never Opera kind to me?!" and I truly understand you :) But let us be kind to Opera once again: 
to make our transparent background work on Opera we need several more CSS tweaks:  Master.css

/* transparency support for Opera */
.modalOpera
{
background-image: url("maskBg.png") !important;
}

that's it! Opera does not understand CSS transparency, but it fully supports .png transparency, therefore a transparent mask as a background will make our ModalDialog work equally good in Opera. 
there is one remaining issue here, we need to selectively apply this class only if and only if the user agent is Opera. That is other browsers, such as Mozilla, does not require this transparency hack and we should not use "modalOpera" class if our user agent is one of them. We will address this issue in a second. 
The Script
first of all we need to prepare the Modal Dialog at page load:  window.onload=function()
{
  /* Sweep unnecessary empty text nodes. */
  DOMManager.sweep();

  /*
  * Attach supporting css bind required
  * classes for transparency support in Opera.
  */
  addExtensionsForOpera();

  /* Attach opacity css. */
  attachOpacityCSS();

  /* Adjust height. */
  adjustHeight();

  /* Create the modal dialog */
  g_Modal=new ModalDialog("ModalBG","DialogWindow",
  "DialogContent","DialogActionBtn");


  /* Bind an event listener to double-click event. */
  EventHandler.addEventListener(document,"dblclick",document_dblclick);



  /* Re-adjust height on window resize */
  EventHandler.addEventListener(window,"resize",window_resize);
};

sweep is a utility method of sardalya's DOMManager object. It removes empty text nodes from the DOM structure. 
Now let us look at other methods one by one  function addExtensionsForOpera()
{
  /* classes for opera */
  var ModalBG=new CBObject("ModalBG").getObject();
  if(typeof(window.opera)!="undefined")
  {
  ModalBG.className="modalOpera";
  }
}

As seen, we only append "modalOpera" className to the "ModalBG" if the user agent is Opera.

Note that we do not sniff the user agent (navigator.userAgent) but do an "object detection" instead (window.opera). 
Browsers love to fool scripts by sending false user agent strings and therefore object detection is the way to go. Although details of it is the subject of an entire article, I can say that browser sniffing is soo '90s. As a rule of thumb always use object detection. 
Then comes attach opacity css piece:  function attachOpacityCSS()
{
  /*
  * CSS for opacity support
  * Note that this can be directly added to the body.
  * If you do not care about blindly adhering to standards
  * you can directly include the rules into Master.css
  *
  * Do I care? Yes and No.(visit
http://www.sarmal.com/Exceptions.aspx

  * to learn how I feel about it).
  */
    var opacityCSS = document.createElement("link");
    opacityCSS.type="text/css";
    opacityCSS.rel="stylesheet";
    opacityCSS.href="Opacity.css";
    document.getElementsByTagName("head")[0].appendChild(opacityCSS);
}
And height adjustment:  function adjustHeight()
{
  /* get the available height of the viewport */
  var intWindowHeight=WindowObject.getInnerDimension().getY();
  var dynModalBG=new DynamicLayer("ModalBG");
  var intModalHeight=dynModalBG.getHeight();

  /*
  * if modal background's height is less than the viewport's
  * available height, increase its height.
  */
  if(intModalHeightThen we create the modal dialog in just a single line:  g_Modal=new ModalDialog("ModalBG","DialogWindow",
  "DialogContent","DialogActionBtn");
"ModalBG" is the ID of transparent background, "DialogWindow" is the ID of modal dialog container, "DialogContent" is where messages is displayed when calling the show method of ModalDialog, and "DialogActionBtn" is the ID of the close button. 
and finally we attach a double-click event to the document which will trigger an AJAX action:    /* Bind an event listener to double-click event. */
  EventHandler.addEventListener(document,"dblclick",document_dblclick);
now let us have a look at document_dblclick method:  function document_dblclick(evt)
{
  /* create an AJAX request */
  var ajax = _.ajax();

  /*
  * Note that _.ajax(); is a shorthand notation
  * for new XHRequest();
  * Visit
http://sardalya.pbwiki.com/Shortcuts
for details.
  */

  /*
  * You can add as many fields as you like to the post data.
  * Normally the server will use this data to create an
  * output that makes sense which may be an XML, a JSON String
  * or an HTML String.
  */
  ajax.removeAllFields();
  ajax.addField("name","John");
  ajax.addField("surname","Doe");

  /* These events will be fired when server posts back a response. */
  ajax.oncomplete=ajax_complete;
  ajax.onerror=ajax_error;

  /* Set a default waiting message. */
  g_Modal.show("Fetching data... Please wait...");

  /*
  * Disable close action if you want to force the user
  * to wait for the outcome of the AJAX request.
  * Although it is generally not recommended
  * this may be necessary at certain times.
  */
  g_Modal.disableClose();

  /* Post data to the server. */
  ajax.get("externalScript.html");

  /* Stop event propagation. */
  new EventObject(evt).cancelDefaultAction();
}

The comments should be self-explanatory.

And finally the two methods that are triggered after the server's post back. /* Triggered when a successful AJAX response comes from the server.*/
function ajax_complete(strResponseText,objResponseXML)
{
  g_Modal.show(strResponseText);
 
  /* Re-activate close button. */
  g_Modal.enableClose();
}

/* Triggered when server generates an error. */
function ajax_error(intStatus,strStatusText)
{
  g_Modal.show("Error code: ["  intStatus  "] error message: [" 
  strStatusText  "].");

  /* Re-activate close button. */
  g_Modal.enableClose();
}

that's it! 
What about those nasty SELECTs ?
ModalDialog object internally handles it, by replacing them with SPAN elements with class "modalWrap" whenever ModalDialog opens. This sorts out the well known "SELECTs bleed through my top layer" issue.  Here is the CSS of it for the sake of completeness:.modalWrap
{
border: 2px #ffffcc inset;
background:#ffffcc;
margin:5px;
}

you can add as many rules as you like to it. The more the SPAN resembles a SELECT element, the better (you can apply width and line-height, set display to inline-table... etc, I did not change it too much to keep it simple) 
for those who wonder how the replacement of those SPANs and SELECTs are done, the corresponding private method is given below. You can observe the source code of the article's zip file for more details.

In the
former version
, we were simply hiding the SELECTs by setting their CSS visibility to hidden.  Having tested it in real-life scenarios, I saw that the "all of a sudden" dissappearance of SELECTs was annoying to some of the users. 
imho, transforming the SELECTs is much better than hiding them completely. 
... And no, I do not want to use IFRAMEs :)  
here follows the code:  _this._replaceCombos=function(blnReplaceBack)
{
var arSelect = document.getElementsByTagName("select");
var len=arSelect.length;
var objSel=null;
var strNodeValue="";
var objSpan=null;
var o=null;

if(!blnReplaceBack)
{
  blnReplaceBack=false;
}

for(var i=0;i"_ModalWrap");
  if(objSpan.exists())
  {
  o=objSpan.getObject();
  o.parentNode.removeChild(o);
  }

  objSpan=document.createElement("span");
  objSpan.id=objSel.id "_ModalWrap";
  objSpan.appendChild(document.createTextNode(strNodeValue));
  objSpan.className="modalWrap";
  objSel.parentNode.insertBefore(objSpan,objSel);

  if(blnReplaceBack)
  {
  new DynamicLayer(objSpan).collapse();
  new DynamicLayer(objSel).expandInline();
  }
  else
  {
  new DynamicLayer(objSpan).expandInline();
  new DynamicLayer(objSel).collapse();
  }
}
};
ConclusionIn conclusion, we modeled and created a draggable DHTML Modal dialog, established an AJAX connection to an external script; we did some cross-browser tweaks to make our application work on as many browsers as possible, and we did some OO coding.
and as always,
Happy coding! 
History

2006-06-02 : Article created.
About volkan.ozcelik



Volkan is a java enterprise architect who left his full-time senior developer position to venture his ideas and dreams. He codes C# as a hobby, trying to combine the .Net concept with his Java and J2EE know-how. He also works as a freelance web application developer/designer.

Volkan is especially interested in database oriented content management systems, web design and development, web standards, usability and accessibility.

He was born on May '79. He has graduated from one of the most reputable universities of his country (i.e. Bogazici University) in 2003 as a Communication Engineer, and is currently about to finish his MBA in a second university. Click
here
to view volkan.ozcelik's online profile.    (2006-6-19:12:59)

 感谢原创者的辛勤劳动,希望对您有所帮助,转载请注明原出处。
 您可能对 [Asp.Net] 的这些文章也感兴趣:

用ASP.NET建立一个在线RSS新闻聚合器
ASP.NET中进行消息处理(MSMQ) 二
关于ASP.NET在IIS中一些问题的经验总结
Upload Files in ASP.NET 2.0
设计模式之Facade——家庭篇
Retrieve data from a web page
不用SQL语句查询DataTable中的数据
设置屏幕分辨率、颜色位数、刷新率
合并DataGrid表头,Merging DataGrid Header Columns
.Net开发过程中安装、调试的常见问题与错误!!!