Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the X & Y position of an iframe from within the Iframe?

I have an iframe on a document. Using javascript, I can get the iframe's width and height and the document's width and height. I now need to get the x,y position of the iframe on the document from within the iframe.

Code is something like:

<html>
<iframe>
var documentWidth = parent.window.innerWidth;
var documentHeight = parent.window.innerHeight;
var iframeWidth = window.innerWidth;
var iframeHeight = window.innerHeight;
var iframeX = ????
</iframe>
<html>

I've tried window.offsetTop/Left, parent.window.offsetTop/Left, window.clientTop, etc and anything else I can find but keep getting 'undefined'.

Both are on the same server so I don't think I have a cross domain issue.

Any ideas?

BTW I can't use JQuery for this. JS Only.

Here is a bit more detail:

<html>
<body>
<div>
<iframe name="iframe/123/Test">
<html>
<body>
<script src="same domain"></script>
</body>
</html>
</iframe>
</div>
</body>
</html>

The script looks like this so far:

// JavaScript Document
var documentWidth = parent.window.innerWidth;
var documentHeight = parent.window.innerHeight;
var iframeWidth = window.innerWidth;
var iframeHeight = window.innerHeight;
var iframeName = window.name;
var iframeX = window.parent.document.getElementsByName(iframeName).offsetLeft;

//Var Dumps
document.write("Document Width: "+documentWidth+"<br>");
document.write("Document Height: "+documentHeight+"<br>");
document.write("Iframe Width: "+iframeWidth+"<br>");
document.write("Iframe Height: "+iframeHeight+"<br>");
document.write("Iframe X: "+iframeX+"<br>");

I get the following results on page in the iframe:

Document Width: 1566
Document Height: 652
Iframe Width: 300
Iframe Height: 250
Iframe X: undefined
like image 367
Keith C. Avatar asked Jan 08 '23 22:01

Keith C.


1 Answers

Since both files are on same server, so you dont have cross domain issue, You can try following solution:

Main Html

<html>
 <body>
   <iframe src='iframe.html' name='iframe_name' id='iframe_id'></iframe>
 </body>
</html>

Iframe Code [iframe.html]:

<html>
  <body>
    <script type="text/javascript">
       var documentWidth = parent.window.innerWidth;
       var documentHeight = parent.window.innerHeight;
       var iframeWidth = window.innerWidth;
       var iframeHeight = window.innerHeight;
       // Get Left Position
       var iframeX = window.parent.document.getElementById('iframe_id').offsetLeft;
       // Get Top Position
       var iframeY = window.parent.document.getElementById('iframe_id').offsetTop;
    </script>
  </body>
</html>
like image 133
Yogesh Salvi Avatar answered Jan 24 '23 04:01

Yogesh Salvi