.load does not work if element is already loaded

0

I have the following problem. I'm using .load to perform an action after loading an iframe

$(document).ready(function() {
   $('iframe').on('load',function()
   { 
       $('#diviframe').fadeTo(200,1);
   });
});

Everything works fine, except if the iframe loads before the code. I came to this conclusion because I tested with iframe with just one word (to load faster) and with several texts (to take a little longer to load). Anyone have any ideas how to solve this?

    
asked by anonymous 17.07.2014 / 03:12

1 answer

1

The problem is that the jQuery code is running before the iframe completes the load.

To ensure that this jQuery code runs after the iframe is loaded, you must use $ (document) .ready. Example:

$(document).ready(function() {
    $('iframe').on('load',function() { 
        $('#diviframe').fadeTo(200,1);
    });
});

Note that if you are using jQuery and there is no reason for the iframe to exist, it might be best to load the content into ajax. Example:

$(document).ready(function() {
    $('iframe').load('http://yoursite.tld/pagina', function() { 
        $('#diviframe').fadeTo(200,1);
    });
});

In addition, it should be noted that

$('iframe').load(...)

and

$('iframe').on('load', ...);

work the same way. In fact, .on () is recommended and exists from jQuery version 1.7 (see link )

    
17.07.2014 / 12:36