I am sure this is old hat to many of you, but it is new to me.

The idea is to display a floating menu when the mouse is over a non-positioned DIV item.

First, I get the position of the DIV item, which works fine. Then I use style.left and style.top to position the floating menu, which works fine on both IE and FireFox, except when the user scrolls the page on FireFox. When the user scrolls, the style.left and style.top seem to position in the floating menu offset by the scrolled amount.

When I try to correct the effect of FireFox scolling, neither window.pageXOffset or window.scrollX provides the amount scrolled. Both pageXOffset and scrollX are zero.

You can see this working (or not working, really) at http://www.statmatics.com/ltf.

Here are some code details. The floating menu:

<style>
  #menu {
    border:none;
    margin: 4px;
    position: absolute;
  }
</style>

<body>
  <div id=menu>
  </div>
</body>

Get the position of the mouseover item

var item = document.getElementById (itemId);
var itemWidth = <code to get width of item>
var itemHeight = <code to get height of item>
var itemLeft = 0;
var itemTop = 0;
var offsetTrail = item;
while (offsetTrail) {
  itemLeft += offsetTrail.offsetLeft;
  itemTop += offsetTrail.offsetTop;
  offsetTrail = offsetTrail.offsetParent;

Show the floating menu and position it near the item

var menu = document.getElementById("menu");
menu.innerHTML = <HTML of the floating menu>
menu.border = "1px solid brown";
var px = (typeof menu.style.left == "string") ? "px" : 0;
menuLeft = Math.floor(itemLeft + 0.7*itemWidth);
menuTop = Math.floor(itemTop - 0.4*itemHeight);
menu.style.left = menuLeft + px;
menu.style.top = menuTop + px;

Any ideas? Thanks for your help.

Paul Richards
Stat-Matics, Inc., Melbourne, Florida

Instead of looking for scroll positions relative to the document, I would read mouse's position to find out where to place the <div>. The event element do the trick, so:

event.clientX is the x position where the event occurred and
event.clientY is the Y position.

Then, the code mydiv.style.left = (event.clientX + 4) + 'px'; will set left position of "mydiv" 4 pixels right to where the mouse is pointing at.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.