0

I have an iframe in my main webpage to which I send different html pages. I would like to create an event, during which a click within the iframe (within the second webpage) triggers an event on the main webpage (within which the iframe sits).

Therefore my question: Is it possible to use a selector in jQuery that refers to an id in a different webpage? I tried using

$("second_webpage.html#div1").click(function() {
        $("#image").css("display", "");
    });

but no success.

Is referring to an element in an external page even possible in jQuery? Are there other ways of doing this?

Thanks in advance!

  • Is not as simple as your attempt. Can only be done if the page in iframe is from same domain as main page. Please clarify that – charlietfl May 28 '18 at 10:46
  • @charlietfl Yes, the page within the iframe is in the same domain. Do you have any suggestions on how to solve this, or ideas what I need to search for? – coder.girl May 28 '18 at 10:49

1 Answers1

0

You need to make two things sure. The iFrame needs to be on the same domain and the iFrame needs to be fully loaded before you execute your Jquery.

If both apply you can use the contents() method.

$("#secondWebPageIFrame").contents().find("#div1").click(function() { ...

Edit:

To ensure the iFrame is loaded you can use the iFrame Load event (in this example with inline javascript):

function onMyFrameLoad() {
   alert('iFrame is loaded');
};

<iframe id="secondWebPageIFrame" src="..." onload="onMyFrameLoad(this)"></iframe>

See this for source and other ways to get the iFrame status: Capture iframe load complete event

Rence
  • 2,900
  • 2
  • 23
  • 40
  • Hi @Sirence, thanks! One question: for the selector, do I refer to the iframe (e. g." #iFrame"), or the web page itself (e. g. "second_webpage.html"). I tried the iFrame itself, and it didn't work, but maybe for a different reason – coder.girl May 28 '18 at 11:15
  • When you add you iframe to your page, you use ' – Rence May 28 '18 at 11:17
  • That's what I had tried before. Does it make a difference that the iframe doesn't have a fixed src="...html"? I use jQuery and the attribute method to change the src, and therefore opening different web pages in the iframe – coder.girl May 28 '18 at 11:34
  • The source should not be relevant for the selector to get the iFrame. However, I do believe if you change the webpage in the iFrame you have to use the iFrame load event again to wait for the content before you can bind actions to it. – Rence May 28 '18 at 11:54