javascriptiframemouse-position

Determine the mouse position inside an iframe, but inclusive of the parent


I have an iframe inside which i detect a right click and pass the mouse event to a function in the parent. Here, (inside the parent function), i have the logic to display a custom context menu and the context menu html markup is inserted into the parent DOM. Thus is need the mouse position according to the viewport (or the parent DOM), but what i received is relative to the iframe.

I tried using offsetTop and offsetParent, but this iterated only till the body tag of the innerpage.


Solution

  • This is the function I used:

    // Define class that will hold Object coordinates
    function CTopLeft(i_nTop, i_nLeft) {
       this.nTop = i_nTop;
       this.nLeft = i_nLeft;
    }
    
    function GetTopLeftFromIframe(i_oElem) {
       var cTL = new CTopLeft(0, 0);
       var oElem = i_oElem;
       var oWindow = window;
    
       do {
          cTL.nLeft += oElem.offsetLeft;
          cTL.nTop += oElem.offsetTop;
          oElem = oElem.offsetParent;
    
          if (oElem == null) { // If we reach top of the ancestor hierarchy
             oElem = oWindow.frameElement; // Jump to IFRAME Element hosting the document
             oWindow = oWindow.parent;   // and switching current window to 1 level up
          }
       } while (oElem)
    
       return cTL;
    }
    

    This is from http://codecorner.galanter.net/2012/02/26/absolute-coordinates-of-element-inside-of-iframe/