1
votes

I have a page that collects click events by event.pageX and event.pageY and I want to map those locations to a 600px by 750px box on another page proportionally. Meaning if there were a screenshot of the other page in the box the marking of the click location would show up visually in the same spot.

I know I have ($('body').width(), $('body').height()), (document.body.offSetWidth, document.body.offSetHeight), and (screen.width, screen.height) at my disposal but I'm not quite sure how best to combine these in order to get an accurate ratio.

Currently I'm just using (in sudo code):

x_ratio = 600 / document.body.offSetWidth
y_ratio = 750 / document.body.offSetHeight

new_x_position = event.pageX * x_ratio
new_y_position = event.pageY * y_ratio

and then the marking of click event inside the box is

<div id='click_marker' 
    style="position: relative; top: new_y_position px; left: new_x_position px;">
</div>

but this doesn't seem to maintain accuracy across browsers and screen sizes. I would like to take a click position in one browser and screen size and be able to accurately map it on any browser and screen size.

How can I consistently and accurately make this calculation?

2

2 Answers

0
votes

First you need to establish the area you want to translate your co-ordinates from. Is it a browser window or a document body? I.e. if do you have a scroll bar, do you want someone scrolling down and clicking at the bottom of the page also appear at the bottom of your 600x750 box or outside? It is not apparently clear from your question.

event.pageX and event.pageY provide position from the left and top edges of the document Therefore using body.offsetWidth will be only consistent when body fills the whole document. Please, check the following fiddle to understand: http://jsfiddle.net/Exceeder/YPHkr/ - notice how going over the right body border will make relative coordinate go over 1.0

Simplest thing to do would be to get $(window).width() and $(window).height() - if the scrolling position does not need to be accounted for. Otherwise you will need to calculate scrolling positions and the algorithm will be a little bit more difficult.

Once you establish that, you need to get the correct width and height. Related question: document.body.offsetWidth variations for different browsers

0
votes

pageX and pageY, gives you co-ordinates relative to the webpage not the screen
Use screenX and screenY to get co-ordinates relative to the screen or clientX and clientY to get them relative to the browsers client window. These event fields may not be available in all browsers.