Webmaster

DHTML : Customised pop-up information boxes
Contents ]
Dr Benton

Positioning an Info Box

As you might already have guessed, the ideal solution for this kind of handling is to make use of layers and their incredible ability to be positioned anywhere. So why not position a layer by means of the mouse pointer's coordinates?

Start by creating the layer:

  4:     <STYLE>
  5:       .bulle
  6:       {
  7:         position : absolute;
  8:         visibility : hidden;
  9:       }
10:     </STYLE>

[...]

19: <DIV CLASS=bulle id=topdeck></DIV>

We will create a style called bulle (lines 4-10), which is referenced in the definition of the info box layer identified by topdeck (line 19). With this style, it will be very easy to hide a layer: it is just a matter of assigning the value hidden to the visibility property.

Although the layer is empty, we can already try to move it. But first we need a way to reference it. Once again, the method used depends on the browser:

25: var skn = (ns) ? document.topdeck : topdeck.style;

[...]

52:   skn.left = x - 60 + 8*Math.random();
53:   skn.top  = y+20 + 8*Math.random();


The skn variable is assigned the appropriate syntax to reference the layer, either for Netscape or for Internet Explorer, depending on the result of the detection. To avoid having to duplicate all the functions, we will use this variable when we want to access the layer.

We can now complete the get_mouse() function to support the moving of the info box (lines 52 and 53). This is not difficult. We just need to update the left and top properties of the topdeck layer. They are assigned the value of the x and y variables (the mouse coordinates), respectively. To avoid the info box and the mouse pointer overlapping, we will slightly offset the former to the left (-60) and downwards (+20).

Now we will add another value using 8*Math.random() to give the layer a vibrating effect. If this shaking gets on your nerves, simply remove the relevant instructions (lines 52 and 53) and the info box will then smoothly follow the mouse pointer without any convulsions.

Random numbers in JavaScript. The Math.random() function returns a floating point number between 0 and 1 (for instance 0.2 or 0.1415926). To obtain a number between 0 and 8, you just need to multiply the returned result by eight.



  1   2   3   4   5   6   7