Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery finding an element within Iframe (by its text) and adding .click function to it

I have a webpage (A) and I am embedding (A) to my mainpage (B) using iframe. This (A) contains a link which closes the browser window:

<a href="" onclick="window.opener = window;
    window.close();
    return false;">Close The Page</a>

Since I embedd (A), the close ability in (A) is no more functional. What I need to do is, when this link is clicked from (B), I want to hide my iframe, in other words make it look like closing. So I have to reach that link in the iframe and understand if it is clicked or not (B)?

Help please.

Thanks

like image 933
stckvrflw Avatar asked Oct 02 '09 09:10

stckvrflw


1 Answers

I'm thinking the following will work. We're basically performing a "find" on the contents of your iframe. Once we find the link we want, we bind an event to it that will close the proper iframe in the parent document. Note that your iframe must be on the same domain as your parent page, or you will not be able to access its elements. Additionally, I added a class to the link to make it easier to selection. I suggest you also do this.

$("#iframeID").contents().find("a.closeWindow").bind("click", function(){
  $("#iframeID", top.document).hide();
});

If you absolutely need to base the binding on the text of the link, you'll have to cycle through the links to find the proper one:

$("a", $("#iframeID").contents()).each(function(){
  if ($(this).text() == "Close The Page") {
    $(this).bind("click", function() { 
      $("#iframeID", top.document).hide(); 
    });
  }
});
like image 107
Sampson Avatar answered Oct 28 '22 14:10

Sampson