Create Pop-Up Notes with DHTML Article

When we talk about Dynamic HTML, we’re really talking about using a scripting language like JavaScript to change Cascading Style Sheets on the fly. DHTML is the fusion of HTML coding and classic object-oriented programming.

This tutorial will illustrate that concept, and help you understand how JavaScript objects map to HTML elements on your Web page.

Along the way we’ll learn how to create a useful DHTML script: a pop-up note like the one shown here. This simple script creates a yellow post-it note when a user clicks on a link. When the users clicks on the word “NASA,” the note tells them that NASA is short for the National Aeronautics and Space Administration.

This script is handy for creating a footnote, a sidebar to an article, or to define an acronym like we have here.

A good way to understand how our pop-up note works is to first create the page using CSS alone, without the JavaScript component. Then we can manually change the CSS properties to understand the role JavaScript plays in the process.

The CSS Component

Let’s start by creating a simple Web page that includes our pop-up note.

To get the most out of this tutorial, I encourage you to work along with me using your favorite HTML editor. You should be able to copy-and-paste the sample HTML code shown in this article.

You can also check our example at each step using your browser. For now, please use Internet Explorer Version 5 or higher to do this. To make it easier to follow my examples, I’ll first create our DHTML script in a way that only works for Internet Explorer. We’ll add compatibility with other browsers as the last step.

So let’s get started. Use the code below to create our simple Web page.

<html>
<head>
</head>
<body>
<p>The space program is run by <a href="#">NASA</a>.
<table bgcolor="yellow" width=250 cellpadding=6 cellspacing=0 border=1 >
<tr>
<td>
<p>The <b>N</b>ational <b>A</b>eronautics and <b>S</b>pace
<b>A</b>ministration.</p>
<a href="#">Close</a>
</td>
</tr>
</table>
</body>
</html>

This creates the static Web page shown below, with the yellow table appearing directly below our other page content. Notice that the pop-up note is always present, and it isn’t placed where we want it to appear.

965_note1

Now let’s apply a style sheet to the yellow table. This allows us to position the table on the page so it looks like a pop-up attached to the word “NASA.” The bold text below shows the new addition to our HTML code.

<html>
<head>
</head>
<body>
<p>The space program is run by <a href="#">NASA</a>.
<div id="n1" style="position:absolute; left:180; top:25; z-index:1;" >
<table bgcolor="yellow" width=250 cellpadding=6 cellspacing=0
border=1 >
<tr>
<td>
<p>The <b>N</b>ational <b>A</b>eronautics and <b>S</b>pace
<b>A</b>ministration.</p>
<a href="#">Close</a>
</td>
</tr>
</table>
</div>
</body>
</html>

All we’ve done here is wrap a DIV element around the yellow table. The DIV tag has a STYLE attribute that positions the table on the page. We’ve set four CSS properties in the STYLE attribute:

  • Position:absolute — This tells the browser that we’re positioning the box with respect to the top left corner of the browser window.
  • Left:180 — This tells the browser to place the table 180 pixels from the left edge of the browser window.
  • Top:25 — And this places the table 25 pixels from the top of the browser window.
  • Z-index:1 — Finally, this tells the browser to place the table in front of our other page text.

Of these CSS properties, z-index probably causes the most confusion for designers who are new to style sheets. It defines a depth dimension for our page and determines which elements are placed in front of which other elements. By default, all page elements have a z-index of zero, so setting the z-index of our yellow table to 1 ensures that it appears in front of our other text.

Now save and view the Web page. It should look like the picture below. This is exactly the way our pop-up note appears after visitors click on the NASA link.

965_note2

Next we’ll add another property to our STYLE attribute, as shown below.

<div id="n1" style="position:absolute; left:180; top:25;
z-index:1;visibility:hidden;">

This adds a new visibility property and sets it to hidden. This means that the browser will hide everything inside the DIV element, and so the yellow table will be invisible. Try it and see for yourself.

After you’ve viewed the page this way, edit it again and change the value of the “visibility” property to “visible.” Save the page and again view it in your browser. It should once again look like the picture above, with the pop-up note being visible.

So the operation of our DHTML script is really pretty simple: we position a colored table in the appropriate spot using CSS, and then show or hide the table by changing the CSS visibility property.

Having done this manually, the next step is learning how to use JavaScript to automatically change the visibility property when the user clicks on the appropriate links.

The JavaScript Component

A key concept in DHTML is that every HTML element on the page has a corresponding JavaScript object. And just as each HTML element can have one or more CSS properties, each JavaScript object should likewise have a corresponding object property for each of these CSS properties.

That’s the theory, at least. In practice not all browsers will provide a JavaScript object for every HTML element, and even if they do there isn’t always a one-to-one correspondence between CSS properties and JavaScript properties. That’s especially true with Version 4 browsers.

Fortunately all Version 4 and higher browsers associate a JavaScript object with each DIV element on your page, and they also provide an object property that lets you control whether the DIV element is visible. The hard part is figuring out how to access this JavaScript object and set its properties.

Let’s see how to access the appropriate object in Internet Explorer.

First, the JavaScript object corresponding to our DIV element is called simply “n1.” Why that name? Because our DIV tag includes an ID attribute that sets ID="n1." By doing this we assigned a unique name to the element, and that becomes the name of its corresponding JavaScript object.

To access the n1 object, insert this script inside the HEAD section of the Web page:

<script language="JavaScript">
<!--

function showObject() {
document.all['n1'].style.visibility = "visible";
}

//-->
</script>

This creates a function called showObject() which sets the n1 object so that it’s visible.

Our new function accesses the JavaScript object by using the document.all array. This array contains all the JavaScript objects for all the HTML elements on our page. We use the ID of our DIV tag to reference the correct entry in this array.

Once you understand the document.all array, the rest of the showObject() function should be easy to follow. The code closely matches the way we earlier set the STYLE attribute for our DIV tag. So this JavaScript code:

document.all['n1'].style.visibility = "visible";

...is just the equivalent of this HTML code:

<div id="n1" style="visibility:visible;">

To actually call the showObject() function, we’ll need to change the NASA link to call the JavaScript function. Do this as shown below.

<p>The space program is run by <a
href="javascript:showObject();">NASA</a>.

If you’re still working along in your HTML editor, make this change to your page and save it. When you view the page in your browser, the pop-up note should initially be hidden, and appear when you click on the NASA link. If your pop-up note is visible when the page first loads, make sure that visibility is set to “hidden” in your style sheet.

Now let’s expand our JavaScript by adding a hideObject() function to our script, as shown below. This function simply reverses the work done by showObject().

function hideObject() {
document.all['n1'].style.visibility = "hidden";
}

Since this function makes our pop-up note disappearwe want to tie its execution to the user clicking on the “Close” link. Do this by changing the link as shown below.

<a href="javascript:hideObject();">Close</a>

Now the pop-up works the way we want, at least under Internet Explorer.

Working with Other Browsers

Let’s expand our script to work for more browsers. Start by adding three lines of code at the beginning of the script. The new lines are shown in bold below.

<html>
<head>
<script language="JavaScript">
<!--
ns4 = document.layers;
ie4 = document.all;
nn6 = document.getElementById && !document.all;

function hideObject() {
...

This very useful block of code lets us sense the capabilities of the browser and tells us which version of the Document Object Model (DOM) to use. That helps us figure out how to find the n1 JavaScript object for this particular browser.

If the page is being viewed in Netscape 4, a browser that supports document layers, then this code will set the ns4 variable. Only Internet Explorer supports the document.all array we used earlier, so if the browser supports this the ie4 variable will be set. Likewise the code applies a separate test to determine if the browser is really Netscape 6, and sets the nn6 variable if so.

Next rewrite the hideObject() function as shown below.

function hideObject() {
if (ns4) {
document.n1.visibility = "hide";
}
else if (ie4) {
document.all['n1'].style.visibility = "hidden";
}
else if (nn6) {
document.getElementById('n1').style.visibility = "hidden";
}
}

This divides the function into three distinct sections: one used when Netscape 4 is the browser, another used when Internet Explorer Version 4 or higher is the browser, and still another used when Netscape 6 is the browser.

Each section uses the appropriate method of accessing the n1 object for that particular browser. Notice that these methods are all different. In fact, for Netscape 4 even the value used to set the visibility property is different ("hide" instead of "hidden").

These differences are a big part of the reason why DHTML can cause lots of browser compatibility problems.

Finally, let’s change the showObject() function to likewise work for all the major browsers.

function showObject(id) {
if (ns4) {
document.n1.visibility = "show";
}
else if (ie4) {
document.all['n1'].style.visibility = "visible";
}
else if (nn6) {
document.getElementById('n1').style.visibility = "visible";
}
}

Again, this uses a different block of code for each browser’s implementation of the DOM.

Positioning By Mouse Click

In its current form this script is a bit brittle. That’s because we’re using absolute coordinates to position our pop-up note over the word “NASA.” If visitors have changed their browser settings to use a larger or small font, the word NASA will appear in a different spot on the page, and our pop-up won’t appear in the right spot.

The cure for this is to detect the mouse coordinates when visitors click the NASA link, and then position the pop-up note at those coordinates.

To do this, first modify the NASA link as shown below.

<A href="javascript:;" onClick="showObject(event);">NASA.</A>

Notice that the call to showObject( ) is now tied to an onClick event, and the function now receives an event object as an argument. This allows us to access data about the mouse click event.

Next we need to update showObject() to change the coordinates of the pop-up note. The code below shows our updated function.

function showObject(e) {

if (ns4) {
document.n1.visibility = "show";
document.n1.left = e.pageX;
document.n1.top = e.pageY;
}
else if (ie4) {
document.all['n1'].style.visibility = "visible";
document.all['n1'].style.left = e.clientX;
document.all['n1'].style.top = e.clientY;
}
else if (nn6) {
document.getElementById('n1').style.visibility = "visible";
document.getElementById('n1').style.left = e.clientX;
docume.getElementById('n1').style.top = e.clientY;
}
}

Here we’ve declared a local variable “e” which is passed the event object. We then use the object properties clientX and clientY to get the top and left coordinates of the mouse click (notice that these are called pageX and pageY in Netscape 4 — yet another compatibility issue).

We use these coordinates to set the top and left properties of our n1 object, and our pop-up note will appear in the right place.

And that’s it. We now have a DHTML script that works the way we want.

Don’t Forget Compatibility

We’ve gone to great lengths to make sure our DHTML script works with the last two versions of the major browsers. But what about older browsers? What about Opera or WebTV? What about people with disabilities who use a screen reader?

The number of people falling into any of these categories is small. In fact, they probably represent less than 2% of your total audience. But that’s still a lot of people, and in today’s environment most companies would love a 2% boost in revenue.

While I like DHTML, I always warn about its potential compatibility issues. Like any thing on your Web page, you should make sure it degrades gracefully if someone uses a browser that doesn’t understand your script.

That means it’s a good idea to use pop-up notes only to provide supplemental information. Never put critical info inside one of these notes.

And any time you use DHTML, it’s a good idea to test your pages by viewing in as many browsers and browser versions as possible. If you can’t do that, then at least view them with JavaScript turned off, just to make sure the page still works.

Extending Our Script

Note that in its current form this script doesn’t scale very well. Since we’ve hardwired our JavaScript code to reference the n1 object, our pop-up will only work if you name the DIV element on your page named ‘n1.’ If you name it something else, the script won’t work.

More importantly, what you want to have more than one pop-up note on your page? The current form of the script only works for a single pop-up.

I did this to simplify the script, just so it’s easier to understand how our JavaScript code is manipulating style sheets. Next month we’ll extend this script to work for any number of pop-up notes. Along the way, we’ll learn how to store JavaScript objects in variables, and how to reference them throughout our code.

Win an Annual Membership to Learnable,

SitePoint's Learning Platform

No Reader comments

Comments on this post are closed.