Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Target parent div containing iframe from iframe

So basically I have something like this

<div class="iframe-holder">
    <span></span>
    <iframe src="iframe.html" width="200" height="200"
</div>
<div class="iframe-holder">
    <span></span>
    <iframe src="iframe.html" width="200" height="200"
</div>
<div class="iframe-holder">
    <span></span>
    <iframe src="iframe.html" width="200" height="200"
</div>
<script>
    function where_am_i(iframe_parent_div,msg){
        $(iframe_parent_div).find('span').html(msg);
    }
</script>   

and then in my iframe-holder.html I basically have this

<a href="#" id="msg">Show Message In Parent Div</a>
<script>
    //i want to basically imp
    $('msg').click(function(event){
        event.preventDefault();
        var iframe_parent_div=???;//how do I get this?
        parent.where_am_i(iframe_parent_div,'This is where this iframe is');
    });     
</script>

So basically my question is how can I target the parent div (div.iframe-holder) of the iframe instance I am clicking the "Show Message" button from? Is this even possible?

I know that I can send through the source a variable with the index i.e. iframe.html?index=0 for the first iframe.html?index=1 for the second and so on but this is not a viable solution for me because in the iframe there is going to be a lot of navigating to different pages so passing around to all the pages the index is not an option.

like image 962
Zaptree Avatar asked Mar 26 '12 17:03

Zaptree


2 Answers

Do:

var iframe_parent_div = window.frameElement ? window.frameElement.parentNode : null;
like image 178
Prusse Avatar answered Nov 14 '22 21:11

Prusse


You could write a function in the parent document that takes the iframe's name as a parameter and then get the iframe-holder div from there. Something like this should suffice:

Code in Parent Document

var findIframeHolder = function (name) {
    var $frame = $('iframe[name="' + name + '"]');
    var $frameParent = $frame.parent();
};

Code in IFrame to Call Parent Function

parent.findIframeHolder(window.name);
like image 44
xcopy Avatar answered Nov 14 '22 23:11

xcopy