Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get absolute mouse position from inside iframe

I have a webpage with an iframe rendering another page (same domain). I need to get the mouse position in relation to the parent document. Keep in mind the iframe can scroll both ways. I've tried using offset with no 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....
 })
like image 279
mariob_452 Avatar asked Jan 22 '15 19:01

mariob_452


2 Answers

One way to do it would be to get the position of the iframe in the parent window and add it to the mouse position 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);
})
like image 170
quik_silv Avatar answered Oct 23 '22 06:10

quik_silv


event.clientX, event.clientY do not work in every browser. However, jQuery has a solution which does. Also, what do you do when your iframe is inside another iframe? I have a solution which works cross browser with nested iframes.

GetPosition: function (event) {
    var $body = $("body");

    var offsetLeft = event.pageX - $body.scrollLeft();
    var offsetTop = event.pageY - $body.scrollTop();

    if (window != parent.window) {
        // event was fired from inside an iframe
        var $frame = parent.$("iframe#" + window.frameElement.id);
        var framePos = $frame.position();
        offsetLeft += framePos.left;
        offsetTop += framePos.top;
    }

    if (parent.window != parent.parent.window) {
        // event was fired from inside an iframe which is inside another iframe
        var $frame = parent.parent.$("iframe#" + parent.window.frameElement.id);
        var framePos = $frame.position();
        offsetLeft += framePos.left;
        offsetTop += framePos.top;
    }

    return [offsetLeft, offsetTop];
}

I wish this were a perfect solution. It works if your iframe is positioned in a fixed layout or absolutely positioned as a modal dialog. However, if your iframe is inside another absolutely positioned container, you will have to get the .position() of that container as well and add it to the total offsets.

like image 22
Jason Williams Avatar answered Oct 23 '22 08:10

Jason Williams