Determine if an element in an iframe is visible on the screen

I need to determine if an element in an iframe is visible on the screen. (if it is on the visible part of the screen) I mean that the page can be very long and the user must scroll to see the item

index.html

<html> ... ... <iframe src="iframe.html" /> ... ... </html> 

iframe.html:

 <html> ... ... <div id="element"></div> .... ... <script type="text/javascript"> var el = document.getElementById('element'); if (isElementVisible(el)) { // do something } </script> </html> 

How to write such a function isElementVisible ()?

+7
source share
1 answer

Here is an example of what you are trying to achieve.

Working example

Iframe only

Basically, this is a function that should go into your iframe :

 function isElementVisible(element) { var elementPosition = element.offset().top; var currentScroll = window.parent.$("iframe").contents().scrollTop(); var screenHeight = window.parent.$("iframe").height(); var visibleArea = currentScroll + screenHeight; return (elementPosition < visibleArea); } 

Run your checks using the scroll event handler.

 $(window).scroll(function(){ if( isElementVisible( element ) ) // Perform your code. }); 

This works by assuming that the iframe is in the same domain as the parent. I use jQuery for convenience.

+3
source

All Articles