Another useful pair of values that can be obtained from the Browser Object Model is the current position of the mouse cursor within the web page. Again this is something where not all browsers load the same field with the information that we are after and so we need to use feature sensing to test which of the different places that we can get the information from.
Again as with determining the viewport size the main difference is between Internet Explorer and other browsers however we don't need to know which browser that it is since whichever of the fields is populated with a non-zero value will be the one that we can use to calculate the values that we want. In this case the browsers either give us clientX and clientY as the position within the viewport or pageX and pageY as the position within the page (some browsers give both). Where we have the position of the mouse within the viewport we can add the scroll position of the page within the viewport to it to obtain the position within the page.
The scroll position is loaded into a different place in IE depending on whether the page uses a strict doctype or not. Other browsers load the information into both places and so we can use whichever contains a non-zero value.
function mouseX(evt) {return evt.clientX ? evt.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) : evt.pageX;}
function mouseY(evt) {return evt.clientY ? evt.clientY + (document.documentElement.scrollTop || document.body.scrollTop) : evt.pageY;}
Note that if this code is used from within a page loaded into an iframe then the position that it returns will be incorrect unless the iframe starts at the top left corner of the page.
