Implementing Dialog Boxes

an article added by: Sonja Lande at 06012007


In: Categories » » AJAX » Implementing Dialog Boxes

As the previous article hinted at, you can use a div element as a content block that mimics the behavior of a dialog box. This article looks more specifically at implementing effective dialog boxes in modern Web applications. Problem You want to implement effective dialog boxes in Web applications. Theory The title for this article shows the words “dialog boxes” in quotes, because the div element is not a true dialog box. Instead, it is restricted to the boundaries of the HTML page. Typically, you can place real dialog boxes anywhere on the computer screen. Real dialog boxes are not of interest in this article. What is of interest is how to create an HTML “dialog box.” For example, When writing HTML pages, you can use dialog boxes for a whole host of things, such as

• To provide meta information associated with a hotspot on an HTML page

• To ask for extra information when filling in a form or processing a workflow

• Menus

• To behave as a wait icon You can also use popup windows to indicate failures; popup windows look different from dialog boxes, but the technique used to create them is identical. Solution Two things must happen in order to make a div element behave like a dialog box. First, you must place the div element on the HTML page using absolute coordinates. Second, you need to make the div element aware of mouse movement. The following example places two div elements 100 pixels from the left and 100 pixels from the top of the client browser window.

   Source: /website/ROOT/ajax articles/dhtml/divdialogessentials.html
 <html>
 <head>
 <title>DIV dialog  essentials</title>
 </head>
 <style type="text/css">
 .background1 {
 background-color: cyan;
 }
 .background2 {
 background-color: blue;
 }
 </style>
 <script type="text/javascript">
 </script>
 <body onload="Init()">
 <div class="background1"  style="left:100px;top:100px;position:absolute">
 Begin
 <div class="background2"
 style="left:100px;top:100px;position:absolute">
 hello
 </div>
 End
 </div>
 </body>
 </html>

The example HTML code contains two div elements, one nested within the other. Ignore the class attribute, as it is used to color the div elements. Instead, look closely at the style attribute, which has three properties: left, top, and position. The position property and the absolute value indicate that the positioning of the element uses absolute coordinates. The absolute coordinates of the top left-hand corner are given by the properties top and left, respectively. The width and height, which indicate how wide and high the div element will be, are missing. When these properties are missing, the browser dynamically calculates the width and height. In the HTML code example, one div element is encapsulated within the other. Both of the div elements are placed 100 pixels from the top and 100 pixels from the left. At first glance, the absolute coordinates would indicate that both div elements are located in the same location. However, this is not what the browser displays.

The two div elements are not on top of each other, but rather one is relative to the other. That is a bit puzzling; the attribute position is set to absolute, so the coordinates should be absolute. The real question is, “What is absolute?” For example, do you need to calculate all absolute coordinates with respect to the parent element? Imagine if a div element that is not positioned using absolute coordinates contains a div element that is positioned using absolute coordinates. Which coordinates would the contained div element use? The answer is that it would use the last element that is either positioned: absolute or position: relative (position: inherit is the default). This is how you get absolute positioning within relative positioning. Using coordinates makes it possible to have a div element appear and display its information like a dialog box. You could add functionality where a link in the “dialog box” would hide the popup dialog box. To be able to know where to make a dialog appear, you need to capture the onclick message and process it. The following source code makes a div element appear where users click on the screen. The div element contains a link that is used to hide the div element.

   Source: /website/ROOT/ajax articles/dhtml/clickappeardiv.html
 <html>
 <head>
 <title>DIV dialog  essentials</title>
 </head>
 <style type="text/css">
 .background {
 background-color: cyan;
 }
 </style>
 <script type="text/javascript">
 function DisplayDiv( evt) {
 evt = (evt) ? evt: ((event) ? event : null);
 x = evt.clientX;
 y = evt.clientY;
 var element = document.getElementById(  "display");
 element.style.left = x;
 element.style.top = y;
 element.style.display = "block";
 }
 function HideDiv() {
 var element = document.getElementById(  "display");
 element.style.display = "none";
 }
 </script>
 <body onclick="DisplayDiv(  event)">
 <div id="display"  class="background"
 style="width:100px;height:100px;position:absolute;display:none">
 hello some text <a href=""  onclick=" HideDiv()">Hide me</a>
 </div>
 </body>
 </html>

In the example HTML page, the body is a single div element, which is not displayed when the HTML page is loaded. The single div element is the div element that will be placed somewhere in the HTML page when the mouse is clicked. Notice the width, height, and position properties are assigned in the declaration of the div element. These properties are defaults that you can set at design time, thereby reducing the amount of code you need to define when displaying the div element.

The code example contains two functions: DisplayDiv and HideDiv. The function DisplayDiv is used to show the div element. The function HideDiv is used to hide the div element. The body.onclick handler calls the function DisplayDiv. The body element is used because the onclick event bubbles upward from child to parent, and the div element should be placed somewhere on the displayed HTML page. The function HideDiv is called by clicking on the link that is displayed when the div element is displayed. When the HTML page loads, users are presented with a blank screen. When they click anywhere on the screen, the body element captures the click event and passes the event to the function DisplayDiv. In the implementation of DisplayDiv, the event object evt is tested using a single line. The single line is necessary for cross-browser compatibility. Once the complete event object has been retrieved and assigned to evt, it is assumed that a mouse event is being sent. A browser-sent mouse event has the properties clientX and clientY, which contain the coordinates of the click in the context of the HTML page.

The coordinates position the div element using the style.left and style.top properties. After the div element has been positioned, you display it using the property style.display. You can hide the div element by clicking on the Hide me link, which then results in a blank HTML page. The displaying and hiding of the div element is fairly elementary, but there is a hidden gotcha. If a div element uses absolute coordinates and is encapsulated within another div element that uses absolute coordinates, then setting the coordinates will result in an incorrectly positioned element. This happens because the click event uses coordinates relative to the browser, and the encapsulated div element uses coordinates relative to the parent element. To remedy this problem, you need to reference different properties, as the following rewritten DisplayDiv function illustrates:

   function DisplayDiv ( evt) {
   evt = (evt) ? evt: ((event) ? event : null);
   if(  evt.layerX) {
   x  = evt.layerX;
   y  = evt.layerY;
   }
   else  if( evt.offsetX) {
   x  = evt.offsetX;
   y  = evt.offsetY;
   }
   var element = document.getElementById(  "display");
   element.style.left = x;
   element.style.top = y;
   element.style.display = "block";
   }

The bold code represents the code used to find the coordinates of the click event relative to the element being clicked. The code has two tests for the existence of either layerX or offsetX. If layerX exists, then you’re using aMozilla-compatible browser, and if offsetX exists, then you’re using Microsoft Internet Explorer. This modified code will work in simple situations, but it is not reliable, because the coordinates are relative to the element being clicked. For example, if you have a div element encapsulated within a div element encapsulated within a div element, and you click on the middle div element, the relative coordinates will be wrong. In a nutshell, once you begin using absolute coordinates within elements that are positioned using absolute coordinates, you’re going to have problems figuring out the real position. Instead, use clientX and clientY, and calculate the absolute coordinates of the HTML elements using a recursive iteration. The ability to display div elements wherever users click allows you to implement menu-type functionality. You can implement error-display handlers and other informational messages that need to be positioned. The only thing you cannot do is display amessage or functionality that you can drag to another position on the HTML page. To do that, the simplest solution is to implement the mouse-down, mouse-move, and mouse-up events. This sounds simple, but it requires quite a bit of extra work to do it robustly.

For starters, you can’t use the onclick event, because this event is sent when the mouse button is released. To implement a dragging operation, you must capture the onmousedown, onmousemove, and onmouseup events. The remainder of this article uses a precanned solution, because quite a few details are involved, and you can apply this base solution in multiple contexts. The solution is to use a file from aWeb site called Dynamic Drive (or, dom-drag.js),4 which only requires users to specify which HTML element should be draggable. The dom-drag.js implementation handles all of the lower-level mouse click event details. The toolbar is recognized as a hotspot used to drag the div element around the HTML page. It isn’t necessary to define a div element using the traditional dialog box notation. The following HTML code, shows how you can define a div element as a hotspot:

   <html>
   <head>
   <title>Drag DIV</title>
   </head>
   <script type="text/javascript"  src="/scripts/jaxson/dom-drag.js"></script>
   <style type="text/css">
   .dialogbox {
   background-color: cyan;
   border: 1px solid black;
   color: black;
   padding: 0px;
   position: absolute;
   }
   .dialogtitle {
   background-color: blue;
   color: white;
   font-weight: bold;
   padding: 2px 2px 2px 2px;
   }
   .dialogcontent {
   padding: 2px;
   }
   </style>
   <script type="text/javascript">
   function Init() {
   Drag.init(document.getElementById("example"));
   }
   </script>
   <body onload="Init()">
   <div id="example"  class="dialogbox" style="left:100px;top:100px;">
   <div class="dialogtitle"  style="width:200px;">
   <center>Drag Me</center>
   </div>
   <div class="dialogcontent" style="width:200px;">
   <a href="">link</a> any  content</div>
   </div>
   </body>
   </html>

Notice how much layout code and script code exists. The layout code outnumbers the script code, which is what will most likely happen in your dialog box implementations. With the dom-drag.js solution, your primary focus is on adding value in terms of look and feel. The dom-drag.js solution doesn’t require using a div element, as you could have created a draggable table element. Remember the following things when implementing dialog boxes:

• To implement a dialog box in HTML, use absolute coordinates; the properties top, left, and display; and onclick or onmousedown, onmousemove, and onmouseup mouse events.

• When implementing dialog boxes, you’re going to be confronted with two major problems: getting the right coordinates, and making sure the element that fires the event has some relation to the element that will be manipulated. For example, you don’t want a menu to appear in the top right-hand corner when the bottom left-hand corner is clicked. This behavior can confuse users.

• Always delegate drag-and-drop functionality to another library. This article used the dom-drag.js solution, but plenty of other solutions abound, and you’re advised to try them out.

legal notice

Our website is not responsible for the information contained by this article. Web-articles is a free articles resource.
Suggestion: If you need fresh, daily updated content for your website, feel free to use our service. Click here for more information.

Useful tools and features

link to this article    
If you like this article (tutorial), please link to it from your web page using the information above.

related articles

1. Testing a Dynamic Contract with Ajax
Coding the Contract Using Test-Driven Development Techniques Coding the contract using agile and test-driven development techniques requires writing a number of tests and implementing aMock URL layer. Problem You want to code the contract using these development techniques. Solution To demonstrate, let’s define a use case, implement the use case as a contract, write a test case(s) to implement the contract, implement the contract in the Mock URL, and finally...

2. Testing the Client Side Logic
Problem You want to effectively test your application’s client-side logic. Theory Testing GUI code tends not to be a productive task because of the complications that arise. The main complication is how to test the correctness of a user interface. Imagine a situation where clicking a button causes a table to be filled with data. Now imagine that when a check box is checked and the button is clicked again, a different table is filled with content. The fact that clicking the same button results in two ...

3. Understanding JavaScript and Types
Understanding JavaScript and Types Problem You want to work around the fact that JavaScript does not have types declared for its variables. Theory JavaScript code does not have any variables with a declared type. The lack of typed variables is apparent when you declare functions. That said, not having typed variable declarations does not mean JavaScript has no types or no type safety. Let’s start out with the simple declaration of a function, as illustrated by the following ex...

4. Coding Using Conventions and Not Configurations
Coding Using Conventions and Not Configurations Problem You want to make your JavaScript constructs more efficient by applying the Rails “convention over configuration” principle to them. Theory You may already be familiar with the programming platform Ruby on Rails, which is used to build Web applications. The focus of this recipe is not Ruby on Rails, but one aspect of Ruby on Rails namely, convention over configuration (see http://en.wikipedia.org/wiki/ Ruby_on_Rails for m...

5. Advantage of parameterless functions in JavaScript
Using Parameterless Functions Problem You want to take advantage of parameterless functions in JavaScript. Theory JavaScript functions for the most part have parameters. You may think that the previous sentence states the obvious after all, without parameters, what data could be passed to a function? JavaScript has the ability to declare functions that have no parameters, even though the caller of the function has passed parameters to the function. For example, let’s look at...

6. JavaScripot Functions
Treating Functions Like Objects Problem You want to take advantage of the fact that functions are objects (remember, everything is an object in JavaScript). Theory Many people think that a function is some keyword used in JavaScript. A function is also an object that can be manipulated. Knowing that a function is an object makes it very interesting from the perspective of writing JavaScript code, because the code can treat the function like another other object. This mean...

7. Implementing an Error and Exception Handling Strategy
Implementing an Error and Exception Handling Strategy Problem You want to implement a clean error and exception handling strategy in your applications, to make them run more smoothly. Theory Of course, you might argue that one error is a dialog box and the other is generated in the JavaScript console. The fact that one browser uses a dialog box to show an error and the other does not is a browser issue, not an error issue. A concise way of classifying the two errors is to ...