Over the past several days I’ve been playing around with jQuery, trying to retool a couple things I’ve been working on. This is my first foray into jQueryland and it’s been pleasant thus far. I did, however, run into a confusing little issue with pageX and pageY.

What’s your vector, Victor?

The problem I was running into happened to be using e.pageY and it’s ilk. In my function they were returning the wrong coordinates. At least that’s what I thought. After much searching and patience — and a little frustration — I believe the problem is solved.

At first I didn’t realize just how far off the positioned element was when just using e.pageY and that’s why it was frustrating. After trying other options like offsetY, clientY, and el.offsetTop amongst others, I was no closer to a solution. I finally measured just how far off the positioned element was and low and behold, it matched the offset of the main parent div (in this case #container).

So, now I had to get the #container’s offset — #container is a set width with margin: 0 auto;. Once I had the offset of #container I could subtract that from e.pageY.

Just how did I get #container’s offset? Well, there are two ways I found, after searching, to figure it out.

  • var topOffset = document.getElementById('container')[0].offsetY — meaning, we need to find the element in the DOM and by setting and index (best to go with 0) we could use Javascript’s offsetY and/or offsetX.
  • var containerPosition = $('container').offset(); var containerTop = containerPosition.top; — meaning, using jQuery and it’s native offset() function, we grab the top and left offset of the element in the DOM.

That’s all she wrote

In the aftermath, I would say pageY and pageX were returning the proper coordinates based on the containers they were in. Unfortunately the coordinates weren’t taking the container offset into account. Whether this is a problem with how my Javascript was written I don’t know. At least I know how to solve it.

Leave a Reply