1

So, I have a div (id="content") where I'm loading various other HTML I get from AJAX requests. I want to be able to tell when they have loaded successfully, but the load event does not seem to work with append().

I have this simplified example to illustrate the situation (in the real case, the listeners for the 'load' event are registered in different files which get loaded in the section of the script)

<html>
<head>
    <script
        type="text/javascript"
        src="http://code.jquery.com/jquery-latest.min.js">
    </script>
</head>

<body>
    <div id="content"><div>
    <script type="text/javascript">
        $(document).ready( function () {
            // this does not seem to work
            $("#myDiv").on('load', function () {
                console.log("myDiv loaded");
            });

            // neither does this
            $("#content").on('load', "#myDiv", function () {
                console.log("myDiv loaded by delegation");
            });

            // the content to append will come from the network
            $("#content").append($("<div id='myDiv'>myDiv</div>"));
        });
    </script>
</body>
</html>

Of course, in the real case things are more complex (the loaded data can be anything) so these are not valid options:

  • having a function called after the div has loaded
  • having a function embedded in the loaded code (the code is generated from template files)
Octav Zlatior
  • 451
  • 4
  • 14
  • div doesn't have `onload` event to attach with thus it will not be fired. – Satpal Jul 04 '14 at 09:09
  • Try looking at these: [jQuery callback after append](http://stackoverflow.com/questions/7865657/jquery-callback-after-append), [How to simulate an append callback function?](http://stackoverflow.com/questions/8406705/how-to-simulate-an-append-callback-function), [jQuery function after .append](http://stackoverflow.com/questions/6068955/jquery-function-after-append). – Joe Jul 04 '14 at 09:09

1 Answers1

1

If you get the data from Ajax requests you should actually use the Ajax done() function. Since the call is async, you wont be able to listen to the changes in the div. Another solution would be to add a body delegate on the div and make it listen to the change event.

$("body").delegate("mydividentifier", "change", function(f){});
$.ajax().done(function(f){});
Razvan Soneriu
  • 587
  • 3
  • 7
  • 23