Click for Navigation:
Custom Menu (HTML-code | <STYLE> | <BODY>-Attributes | JavaScript function)
Alert | Yes/No-Decision | Single-line Input | Dialog | Subdialog | Status bar | Sound


How to Provide
User Interactivity

for demos: Ctrl-key + right-click (IE only)


This article shows a number of methods how you can have your visitors not only read your contents but also interact with them. By all experience that will make your contents stick in memory much better than just one-way communication.

In article Online Communication - unlike Writing on Paper it was recommended to provide user interaction. Thus involving your visitors into your contents actively, instead of having them read only passively.

You might wonder now: "Ok, might be a good idea. But how can I do that? And doesn't that mean a lot of effort, that would be better used if I strengthened my contents?"

Fortunately, in DHTML there is quite a number of ways to do that by just a few lines of code extra.

next    top

































Custom Menu

Except for very simple cases, the first step towards user interactivity will always be a menu. By clicking any of its items your visitor can chose which one of the custom operations to be executed.

HTML-code of a Custom Menu

Essentially, a custom menu is just an invisible DIV with a number of hyperlinks. They are disabled and any JavaScript function is called when a hyperlink is clicked:

<DIV style="display:none; … ">
<A href="#" onclick="Action(1); return false"> … (text of menu item 1) … </A><BR>
<A href="#" onclick="Action(2); return false"> … (text of menu item 2) … </A><BR>
<A href="#" onclick="Action(3); return false"> … (text of menu item 3) … </A>
</DIV>

The action to be performed when an item is clicked is associated by:

onclick="Action(…)"

For formal reasons the pseudo-target  href="#"  is needed to a hyperlink. On some browser versions this might trigger an error when it is clicked. Therefore we need to disable it by adding to the  onclick="…"-clause:  ; return false  Thus the browser is told not to do the default operation of this hyperlink = to go to the target.

To let your visitors know the border between the custom menu and the normal contents, you might want to give it a border line. To that effect, add to the DIV's  style="…"-clause for example:  border:1px solid green 

As well you could make it have a different background color. So you should add to the DIV's  style="…"  clause for example:

background-color:yellow

Many other things you can do to make your custom menu look and behave user-friendlier. They all are implemented by additional style clauses.

For more user-friendliness it will be good to remind your readers how to do away with the menu once it is no longer needed (e.g. by another  Ctl + right-click ).

<STYLE> of a Custom Menu

If you want to make this menu behave like a typical menu, you could do that by an extra style declaration, for example:

<STYLE>
<!--
A:hover {color:white; background-COLOR:blue; font-weight:bold; cursor:hand}
-->
</STYLE>

Thus each menu item turns to bold-white color with a blue background color when the cursor hovers over it. Moving over all menu items, this will mimic a "selection bar" (as usual with a menu).

If you have some other hyperlinks in your document that you don't want to change background color when the mouse is hovering over it, introduce a class name, e.g.:

<STYLE>
<!--
.MenuItem:hover {color:white; background-COLOR:blue; font-weight:bold; cursor:hand}
-->
</STYLE>

Now only those hyperlinks will be changed in background color that are coded as

<A class="MenuItem" … >"> … (text of menu item) … </A>

However, by default the background color is changed only as far to the right as the item's text extends. And it has some other deficiencies: On some browsers, a multi-word menu item is not covered fully by that declaration. By default a hyperlink's text is underlined, what you might want to avoid in your menu. So you should bracket an item's text in the following tag:

<NOBR STYLE="width:…; text-decoration:none">alert</NOBR>

If all your menu items are declared to have the same STYLE="width:…" , the background color of each one is changed at the same widths, resulting in a "selection bar"-like appearance.

<BODY>-Attributes of a Custom Menu

Most of your visitors will be used to expect a custom menu being launched when they are clicking the right mouse key. However, in most cases this is already occupied: modern browsers launch their own context menu upon right-clicking. So we need to offset that by an additional rule: Upon normal right-clicking, the browser's context menu is launched just as usual. Upon right-clicking with concurrently pressing the Control-Key, the custom menu is launched.

Fortunately most browsers are asking before they launch their context menu. By returning false to this request, launching the context menu can be suppressed. So we need a global variable  bContextMenu  that is set to  false  when a right-click with Control-key being pressed is detected. When a right-click comes without a Control-key being pressed, it is set to  true .

Setting this global variable can be done by the same JavaScript function that will control the custom menu's behavior. So the complete <BODY> tag of your document looks as follows:

<BODY onContextMenu="return bContextMenu" onmousedown="ToggleMenu()">

JavaScript function of a Custom Menu

First thing we have to do is decide whether the mousedown event was caused by a right-click or not. We can do that simply by checking  if (event.button != 2) return;  Thus any other  mousedown  than that of a right-click is ignored.

Then we need to check for the Control key being pressed. This is done by

if (event.ctrlKey)   bContextMenu = false;
              else { bContextMenu = true; return; }

So, if the Control key was pressed concurrently with the right-click, the global variable  bContextMenu  is set to  false . If not, it is set to  true  and this case is ignored for toggling the custom menu.

In a second step the visibility of the custom menu is toggled: if the menu is currently invisible, it is set to  visible  , and vice versa.

Finally, the menu's attributes  pixelLeft  and  pixelTop  are set to the point located by the current cursor position.

In reality, it's a bit more complicated than presented here. For rather user-friendly placement of the custom menu a bit of a case distinction is required. But for the sake of clarity it was somewhat simplified here.

Altogether, we arrive at the following coding scheme:

var bContextMenu;  // global variable

function  ToggleMenu()
{
  // control browser's context menu

  if (event.button != 2)  return;
  if (event.ctrlKey)   bContextMenu = false;
                else { bContextMenu = true; return; }

  // toggle custom menu's display

  if (menu.style.display == "") 
		menu.style.display = "none";
       else	menu.style.display = "";

  // place custom menu to the current cursor point 
  // (simplified here)

  menu.style.pixelLeft = event.clientY + … ;
  menu.style.pixelTop  = event.clientY + … ;
}

previous    next    top

































Alert

This is the easiest way to provide user interaction. Displays a modal dialog box with a message string and an OK button. It's good for:

  1. Giving feedback to the readers as to the result of internal operations.
  2. Giving the readers control over the timing of internal operations.
  3. Script debugging (= for yourself).
Coding scheme:
alert (["message"])
Parameter:
 message  String to be displayed on screen (optional).
Can also be any combination of string constants + variables/expressions.
If using expressions, make sure they are evaluated first, before the result is concatenated to the string, i.e. bracket them in  (…) .
The displayed message box is sized automatically such as to accommodate all the resulting string.
Title bar: "Microsoft Internet Explorer" (cannot be changed) and an "x"-button
Icon: Exclamation mark (= warning symbol)
Return value: undefined (whether your reader presses "OK" or the "x"-button in the title bar)
Remark: Some care should be taken when placing an 'alert' in a loop. Then the message Box will appear repeatedly, each time blocking all other operations until the reader presses "OK". This can soon get pretty awkward. Then there is no other way to get out of it but to abort the browser application altogether, possibly losing precious data that were not stored before.

previous    next    top

































Yes/No-Decision

This is an easy way to present a message string to the readers and to ask them for a yes/no-decision. Displays a modal dialog box with a message string, an OK and a Cancel-button. It's good for:

  1. Giving feedback to the readers as to the result of internal operations.
  2. Giving the readers control over the flow of internal operations.
  3. Script debugging (= for yourself).
Coding scheme:
confirm (["message"])
Parameter:
 message  String to be displayed on screen (optional).
Can also be any combination of string constants + variables/expressions.
If using expressions, make sure they are evaluated first, before the result is concatenated to the string, i.e. bracket them in (…).
The displayed message box is sized automatically such as to accommodate all the resulting string.
Title bar: "Microsoft Internet Explorer" (cannot be changed) and an "x"-button
Icon: Question mark
Return value:  TRUE  if the user chooses OK, or  FALSE  if the user chooses Cancel or clicks the "x"-button.
Remark: Typical coding scheme:
if (confirm("…"))
     {
       // OK-action
     }
else {
      // Cancel-action
     }

previous    next    top

































Single-line Input

This is an easy way to present a message string to the readers and to prompt them for a 1-line input of any char sequence. Displays a modal dialog box with a message string, an OK and an input field. Good for:
  1. Giving feedback to the readers as to the result of internal operations.
  2. Giving the readers a simple way to interact with internal operations.
  3. Script debugging (= for yourself).
Coding scheme:
prompt (["message"[,"default"]])
Parameters:
 message 

String to be displayed on screen (optional). Can also be any combination of string constants + variables/expressions.
If using an expression, make sure it is evaluated first before the result is concatenated to the string, i.e. bracket them in "(…)".
The displayed message box is sized automatically such as to accommodate all the resulting string.

 default 

Default input (optional; if the first parameter is to be omitted, it must be coded as an empty string "" )
If this parameter is omitted, "undefined" appears in the input field.
If you want to have the input field empty, code an empty string ("") as second parameter.

Title bar: "Microsoft Internet Explorer" (cannot be changed) and an "x"-button
Icon: Question mark
Return value: The contents of the input field if the user chooses OK, or NULL if the user chooses Cancel or clicks the "x"-button.
Remark: Typical coding scheme:
user_input = prompt("…");
// processing of user_input

previous    next    top

































Dialog

This is an easy way of presenting to the readers a dialog of any layout and complexity. Displays a modal dialog box whose layout is determined by a normal HTML-file (usually a <FORM>). Good for:

  1. Giving the readers a very versatile way to interact with internal operations at any complexity.
  2. Script debugging (= for yourself).
Coding scheme:
showModalDialog(URL[,Arguments[,Features]])
Parameters:
 URL  String specifying the URL of the document to load and display. While an empty string is accepted (""), it should be noted that this is useless since once a modal dialog has been opened, it cannot be accessed by the page that opened it. Mandatory parameter.
 Arguments  Variant specifying the arguments to use when displaying the document. This parameter can be used to pass a value of any type including an array of values. The dialog can extract the values passed by the caller from the dialogArguments property of the window object. Optional parameter.
 Features  String specifying the window ornaments for the dialog box. It can be a combination of the following values.
dialogWidth: number Sets the width of the dialog window.
dialogHeight: number Sets the height of the dialog window.
dialogTop: number Sets the top position of the dialog window relative to the upper-left corner of the desktop.
dialogLeft: number Sets the left position of the dialog window relative to the upper-left corner of the desktop.
center: {yes | no | 1 | 0 } Specifies whether to center the dialog window within the desktop. Default: yes
Optional parameter; if the second parameter is to be omitted, it must be coded as an empty string "".
Title bar: depending on the <TITLE> tag in the layout file, and an "x"-button
Icon: none automatically, but you can have any image in the layout file (by <IMG> tag)
Return value: Any number, string, or other value. This is equal to the value of the returnValue property as being set in the layout file (given by URL).
Remark: Typical coding scheme:
user_inputs = showModalDialog("layout_file.htm,"…","… … …);
// processing of user_inputs

previous    next    top

































Subdialog

This is an easy way of presenting to the readers a dialog of any layout and complexity, in parallel to any other screen contents. Displays a modeless dialog box whose layout is determined by <DIV> comprising normal HTML-code (usually a <FORM>). It's good for:

  1. Giving the readers a very comfortable way to intervene at internal operations.
  2. Script debugging (= for yourself).
HTML Coding scheme:
<DIV ID="…" STYLE="display:none; position:absolute; … ">
     <FORM ID="…form_id…" onsubmit="Submit(…form_id…)">
         Input1: <INPUT … >
         Input2: <INPUT … >
            :         :
         <INPUT TYPE="Submit" VALUE="…">
     </FORM>
</DIV>
JavaScript function (simplified):
function Submit(f)
{
   var obj, inputs="";

   for (i=0;  obj = f.children(i);  i++)
    if (obj.name) 
     inputs = inputs.concat(obj.name + '=' + obj.value + '\n');
}
Remarks:
  1. A subdialog is a normal part of the page's HTML-code. So there is nothing like parameters, title bar, return value, etc. All variables can be accessed directly by the JavaScript function.
  2. By default, subdialog and menu are hidden after returning from Submit(…) If you want to keep them visible, code  onsubmit="Submit(…); return false"  .

previous    next    top

































Status bar

A message in the status bar of your readers' browsers is "ephemeral", i.e. it disappears by itself without holding up the user to remove it, such as alert. Therefore it should not be used for critical signals, requiring your readers' full attention.

In JavaScript coding producing a status bar message is just one line of code:

status = …

… is the message string to be displayed on screen. It can also be any combination of string constants + variables/expressions. If using expressions, make sure they are evaluated first, before the result is concatenated to the string, i.e. bracket them in  (…) .

A minor drawback is that the status bar of a browser is not very long, and is even reduced when your readers resize their browsers (exceeding parts of the message string are simply ignored). So, be sure to keep your message string to a minimum.

Example:

Let's assume, you want to display in the status bar continuously the current cursor point. In your HTML coding this would require an attribute in the <BODY> tag:

<BODY onmousemove="Status()" … >

In JavaScript coding the function Status would be one line only:

status = 'x = ' + event.x + '   y = ' + event.y;

previous    next    top

































Sound

Also a sound signal is ephemeral So it is good to signal that a certain point is reached in execution. It is very useful for repeated signaling. In fact, humans tent to hear a pattern of signals and can easily detect any digression from the usual pattern.

Its drawback is its limited information content: An average listener will not be able to distinguish between many sound signals, unless they are pretty long what will not be what you want here).

HTML Coding:

A sound signal needs an image somewhere on the document. Alas, it must be visible on screen. So you should arrange it at any inconspicuous place, and declare it with negligible dimensions:

<IMG id="img" WIDTH="1" HEIGHT="1">
JavaScript Coding:

Then the JavaScript coding for playing a sound file is one line of code only:

img.dynsrc="sound_file"

The sound file can be any of the video formats associated with your readers' browsers. By default it is .wav, .mid and .rmi. Even .avi-files can be used, if you want to present a video clip.

previous    top