954,600 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

elementFromPoint() problems when window has been scrolled .

Hello, All ...
I have an HTML file which contains pages of formated text, all within a 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 ) - 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

seanmc23
Newbie Poster
6 posts since Sep 2009
Reputation Points: 10
Solved Threads: 0
 

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 ....

seanmc23
Newbie Poster
6 posts since Sep 2009
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: