1

I have a function which changes content of the iframe (for instance change the URL of the images). Currently, I bind a function to iFrame's load. Something like:

$('iframe#frame').load(function() { });

The problem is, when I run this and change the src attribute of the iframe, the function runs after all the elements are loaded and then changes it. I want to be able to run the code as soon as the HTML content of the iFrame is loaded to prevent the extra loading time. Is there any way I can achieve this?

Alireza Noori
  • 14,961
  • 30
  • 95
  • 179

1 Answers1

2

Try this

  $.get('https://google.com', function(data){
      var doc = $frame[0].documentElement;
      doc.open();
      doc.write(data);
      doc.close();
      $frame.trigger('ijustchangedthesrc');
  }, 'HTML');

later

  $('iframe#frame').on('ijustchangedthesrc', function(){});

Give your iframe no src to start with.

Fresheyeball
  • 29,567
  • 20
  • 102
  • 164
  • Nope! Tried, doesn't work. It runs before the HTML is changed so I can't access the HTML inside the iframe. – Alireza Noori May 16 '13 at 02:16
  • It's easy, I just set the `src` of the iframe. `$frame.attr('src', 'https://google.com');` – Alireza Noori May 16 '13 at 02:38
  • Thanks. I tried, but the result is the same as `ready`. The event is fired up **before** the HTML is loaded from the server. – Alireza Noori May 16 '13 at 02:50
  • Ok I am getting a better idea of what you need. Try the above. – Fresheyeball May 16 '13 at 04:27
  • Awesome. As soon as I read the first line of your answer, I knew it's gonna work. For some reason I couldn't use the `$frame` jQuery variable and used the code from [this answer](http://stackoverflow.com/questions/997986/write-elements-into-a-child-iframe-using-javascript-or-jquery). In the end it worked perfectly. – Alireza Noori May 16 '13 at 10:19
  • Shweet. Glad to be of help. – Fresheyeball May 16 '13 at 19:02