7

Suppose I have a page with multiple IFrames :

Main Page

<div id='someDiv1' style='display:none; '>
       <iframe id='iframe1' src='iframe1.html'>
           <input id='someinput'></input>
       </iframe>
</div>

IFrame (iframe1.html)

<input id='someinput'></input>
<script>
  function isElementVisible(elem){

  }
</script>

In this scenario how do i check if the element is visible/hidden due to the parent div of IFrame hiding it?

I tried using $('#someinput').is(':visible') but I always get true if I run it inside IFrame. I don't have an option to change the page structure nor execute the script inside parent.

Pushkar
  • 6,990
  • 9
  • 35
  • 57
  • 1
    In pure JavaScript `var is_hidden = parent.document.getElementById("iframe1").parentNode.style.display == "none"; alert(is_hidden ? "I am hidden" : "I am visible");` – hex494D49 Jul 02 '14 at 11:40
  • possible duplicate of [Testing if something is hidden, using jQuery](http://stackoverflow.com/questions/178325/testing-if-something-is-hidden-using-jquery) – newfurniturey Jul 02 '14 at 12:40
  • Not really a duplicate. Please read my complete question. – Pushkar Jul 03 '14 at 02:58
  • 1
    Its vanilla JS, you dont need Jquery for every single line of code you write. –  Jul 05 '16 at 14:44

3 Answers3

9

The document inside your iframe is not aware of the situation in your main page... But I believe you can just 'query' your parent to check if it's visible?

$('#someDiv1', window.parent.document).is(":visible");

or without jquery because you don't really need it..

if(window.parent.document.getElementById("someDiv1").style.display != "none") 
    alert("Visible");
else 
    alert("Hidden");
Tiele Declercq
  • 1,910
  • 2
  • 23
  • 37
  • 2
    Will this work if IFRAME is from other domain than parent document? – Gacek Jun 03 '16 at 12:22
  • As @Gacek brought up, this will not work if the – trysis Oct 11 '18 at 16:30
2

I am not sure if you can access the value/properties of an element within an iFrame I tried accessing the value but its gives "undefined"

Jquery try accessing value from iframe container

var isDivOpen = $("#someDiv1").is(":visible");
//for getting the state of the div : visible/hidden
Austin N
  • 203
  • 2
  • 3
  • 11
0

URL parameters are your friend.

in the iframe1.html put this at the top:

<script>

    function getUrlVars() {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    }
    var test = getUrlVars();
    console.log(test[0]);

</script>

and for your main page use:

<div id='someDiv1' style='display:none; '>
    <iframe id='iframe1' src='iframe.html?visible=yes'>

    </iframe>
</div>
jbyrne2007
  • 576
  • 2
  • 10