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.

Create Pop-Up Notes with DHTML Article

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.

Create Pop-Up Notes with DHTML Article

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.

Replay

Category: javascript Time: 2002-12-05 Views: 0
Tags:

Related post

  • How to create pop-up menu with animation and 2 options 2016-02-02

    I need to create this: but with only 2 options. So far i've found i can do similar things with Dialogs but it is not what i need. Needs to be called with onClick event and since now i have made it work with a Fragment with an ImageView at the bottom

  • Create Pop-Up Box with Custom Field Content Inside the Loop 2014-06-22

    I tried this using ThickBox first, then tried using some code I had that worked on another website... Total failure. The Goal: I have a custom post type (product) with a ton of custom fields. I also have a page that says "display all of these custom

  • Disable a pop up rendered in FF and not with IE 2014-09-29

    when testing with Selenium Webdriver, I'm getting an advertising pop up window with Firefox and not with IE. Actually this pop up is preventing me from doing many other tasks. Is there a way to disable this kind of pop up when creating the Firefox dr

  • AWS Autoscaling: newly created instance is not in sync with other instances 2015-09-16

    I am new to AWS and learning autoscaling feature of aws. i have created one autoscaling group with min instance of 1 and max instance of 1. For experimental purpose whenever i terminate my instance belongs to this autoscaling group that time aws auto

  • Angular 2 Tutorial: Create a CRUD App with Angular CLI 2016-06-27

    Angular 2 is an open source framework for building mobile and desktop applications. Rather than a successor of AngularJS 1.x, Angular 2 can be considered an entirely new framework built on learnings from AngularJS 1.x. Hence the name change where Ang

  • How to create a zip archive with PowerShell? 2009-07-20

    Is it possible to create a zip archive using PowerShell? --------------Solutions------------- If you head on over to CodePlex and grab the PowerShell Community Extensions, you can use their write-zip cmdlet. A pure Powershell alternative that works w

  • A Beginner's Guide to Silverlight with PHP Article 2010-04-29

    In recent years, web developers have been moving increasingly towardsthe development of so-called RIAs, or Rich Internet Applications. These canbe built using any of a number of different technologies, but what they havein common is their goal of rec

  • create a debian installer with custom kernel 2011-11-10

    First what I need to do is install a debian on a 3300mx computer which is based on a vortex cpu. The problem is the debian installer always crash because the required drivers are in the kernel as modules only. So I tried to create a custom kernel wit

  • Can i create a security group with the proper permissions and have farm account run only as a service account? 2011-12-08

    On my SP 2007 environment I been trying to have my administrators not use the farm adm account for their administration and use their own credentials. So we started by creating a security group with local admin rights on the server and determined tha

  • Creating a new environment with one optional argument 2012-06-16

    I want to create a new environment with one optional argument in LaTeX. Here is what I used: \newenvironment{argument}[1][]{% \par \noindent \textbf{Argument#1:} \noindent} {} When there is no argument, it typesets the ':' right after the word 'Argum

  • How to create a squiggle arrow with some text on it in TikZ? 2012-06-18

    I need to define a new command to create a squiggle arrow with some text on it. Something similar to what \xrightarrow command produces but with wiggly arrows as in \rightsquigarrow. The length of the arrow should automatically be adjusted to fit the

  • Print edit/create/delete node link with jQuery 2013-02-07

    Been searching for a while so I came here to ask... How can I print edit/create/delete node links with jQuery? I just want to show the links when I hover over the < li >'s. I already have the hover code... So I really just need to code to get the ed

  • Sync iOS Notes with Exchange 2013-02-25

    Why is it that I can sync Apple Notes with Exchange on Mountain Lion but not with iOS 6? Is there any way to sync iOS notes with Exchange like I can with iOS Reminders? --------------Solutions------------- iOS Notes only supports syncing with iCloud

  • Create a web site with Tex/Latex Support + Preview feature 2013-03-10

    (This is a question that is more or less not a Tex/Latex question, I guess. But it still relates to Tex/Latex.) I want to create a new web site. Here is the goals for that site: It will be used to write things about mathematics. Different from Wikipe

  • How to create a FTP user with specific /dir/ access only on a Centos / linux installation 2013-07-16

    So I'm on a VPS - CentOS Linux installation. I have vsFTPd on the server. I currently have SFTP access to the server via my root user, but am now trying to create a new user with FTP access to a specific directory only on the server, I've done the fo

  • Create a Podcast Feed with PHP 2013-08-09

    In this article, I'll demonstrate how to use PHP to generate a podcast feed. We'll create a simple administrative interface to configure the podcast metadata, add and list episodes, and then go through the generation of the podcast feed itself (which

  • iPhone 5S security: Given someone's fingerprint can I use a 3D printer to create a fake finger with a real fingerprint on it? 2013-09-11

    With such a big deal being made about the iPhone 5S's fingerprint reader (and formerly the Thinkpads' fingerprint readers) I really wonder how secure it is to use fingerprints in lieu of passwords. If you can dust and photograph a roommate's or cowor

  • CMS that creates separate discussion page for each article 2014-03-08

    I'm looking for a CMS (it can also be a specialized CMS, e.g., a blog or a wiki) that should come* with the following functionality. (* I know that this can be done with most CMS, but I'm especially looking for a solution that ships with this functio

  • Own command works not with all LaTeX distributions and LaTeX document classes 2014-09-18

    A new defined command (see below) works on my windows with MiKTeX 2.9 and on a Mac with MacTeX. On another windows (running in a Mac) with an absolute fresh installed MiKTeX and on the same Mac in Mac OS with MacTeX the command doesn't work. We are u

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development

search

Front-end development

Database

development tools

Open Platform

Javascript development

.NET development

cloud computing

server

Copyright (C) avrocks.com, All Rights Reserved.

processed in 3.898 (s). 13 q(s)