0

I have an HTML page containing an iframe and I am trying to write functions on links in the iframe. The functions will make changes in the HTML page...

The following script works on the first link that is clicked in the iframe. But when the iframe chages "src" the function will not work any more.

How can I make it work even if the src of the iframe is changed?

(all pages are on the same domain)

<script type="text/javascript">
  $("iframe").contents().find("a").click(function() {
    alert('Load was performed.');
  });
</script>
1
  • This is how I sloved it: var chooseName = $('iframe'); chooseName.load(function() { chooseName.contents().find('a').click(function() { alert('Load was performed.'); }); }); Note Comment from Omeid Herat below. This script will not work on cross-domain. Not even if it's a subdomain. Stackoverflow rocks! Will definitely use it agin :) Commented Dec 8, 2010 at 13:38

2 Answers 2

1

try to use the .live() method, it binds an event to the existing elements and future elements. When you change the src, you need to bind again the click event to the new links.

I don't know if the .live() method works on a iframe but you can try this:

  $("iframe").contents().find("a").live('click',function() {
    alert('Load was performed.');
  });

Sorry for my broken english!.

i don't know if it will works (sorry I don't have where to test things now), but what happens if you try to bind an function on the onLoad event of your iframe, (even if W3C says that iframe has no events, it appears to be supported by all browsers):

    <iframe src="/my_contents" onLoad="onload_function()"></iframe>
    ...
   <script>
        onload_function(){
          $(function(){
            $("iframe").contents().find("a").click(function() {
              alert('Load was performed.');
            });
          });
        }
    </script>
Sign up to request clarification or add additional context in comments.

1 Comment

The .live() method doesn't seam to work on iframes. Thanks for trying tough. Is there some other way I can bind the click event again? (reload the function)
0

if its the same as your domain it should work if not Because of Some Origin polciy it will not work as its cross-domain.

2 Comments

It works as long as I stay on the same iframe. But if the iframe is reloaded with a new url it doesn't work.
It works as long as I stay on the same iframe. But if the iframe is reloaded with a new url it doesn't work. All URL:s and src are the same domain... Thanks for answering any way :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.