1

Hello, All ...
I have an HTML file which contains pages of formated text, all within a <p> tag, which has an onclick call to a jscript function. This function gets mouse cursor position at the click event, then passes this position to elementFromPoint(pos.x,pos.y) to return my element object, which I then highlight.

I did this using this method because it seemed to work best with my nested elements (always <span>) - sometimes nested 15-20 layers deep. This enables me to easily view the level of nesting, and start and end of this block of clicked text, which can sometimes be hundreds of lines long, within a file which can be thousands of lines long.

I got this working in IE and Firefox, which are the only 2 browsers it will ever be used in. Well, at least I thought I had it working -until I scrolled the page, and suddenly it wasn't working anymore. This bug is the same in both browsers.

function gCO(e) {
  e = e || window.event;
  var pos = getPosition(e);
  var obj = document.elementFromPoint(pos.x, pos.y);
  doHighlight(obj);
}

function doHighlight(ele) {
  if (ele.style.backgroundColor == "pink") {
    ele.style.backgroundColor='';
  }
  else {
    ele.style.backgroundColor="pink";
  }
}

function getPosition(e) {
  var cursor = {x:0, y:0};
  if (e.pageX || e.pageY) {
    cursor.x = e.pageX;
    cursor.y = e.pageY;
  }
  else {
    var de = document.documentElement;
    var b = document.body;
    cursor.x = e.clientX +
      (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
    cursor.y = e.clientY +
      (de.scrollTop || b.scrollTop) - (de.clientTop || 0);
  }
  return cursor;
}


<p onclick="gCO(event)">

Is there a way to compensate for my page scroll offset?

Thanks in advance for any help given,
Sean

Edited by peter_budo: Please do not use CODE SNIPPED option to post question. Use FORUM THREAD!

2
Contributors
2
Replies
5
Views
7 Years
Discussion Span
Last Post by Seyferx
1

I apologize for looking for the easy way out without researching and experimenting a bit further - I figured out the solution and have it working beautifully now in both FF and IE now.

In my getPosition function, for FF, I needed to subtract window.pageXOffset from the e.pageX value - likewise for Y.

ex.:

cursor.x = e.pageX - window.pageXOffset;

For IE, I just needed to remove everything being added onto e.clientX,
ex.:

cursor.x = e.clientX;

Anyway - hope someone else finds this useful ....

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.