Get absolute mouse position from inside iframe

I have a webpage with an iframe displaying another page (same domain). I need to get the mouse position relative to the parent document. Keep in mind that an iframe can scroll both ways. I tried using offset without luck.

$('#iframe').contents().find('html').on('mousemove', function (e) {

     //gives me location in terms of the iframe but not the entire page. 
     var y = e.pageY; 

     //gives me 0
     var y = $(this).offset().top;

     //more code here....
 })
+4
source share
1 answer

One way to do this is to get the position of the iframe in the parent window and add it to the position of the mouse relative to the iframe itself. Extending your code below

var iframepos = $("#iframe").position();

$('#iframe').contents().find('html').on('mousemove', function (e) { 
    var x = e.clientX + iframepos.left; 
    var y = e.clientY + iframepos.top;
    console.log(x + " " + y);
})
+7
source

All Articles