7

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 the page can be very long and user must scroll to see the element

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()?

asked Mar 6, 2013 at 14:41
1
  • Any news with this problem? Commented Mar 10, 2013 at 0:37

1 Answer 1

3

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

Working example

Just the iframe

Basically, this is the function that should go inside 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);
}

Trigger your checks with a scroll event handler.

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

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

answered Mar 6, 2013 at 15:13
Sign up to request clarification or add additional context in comments.

2 Comments

What about handling multiple zIndexes? Let's say you have 3 iFrames at roughly the same position with different zIndexes - how do you determine that one of them is blocking the other two?
You can check the z-index property with jQuery, check the position and the display or visibility in your function. Without seeing the code is a bit difficult to answer, perhaps you can post your own question and post a link here, so I can take a look.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.