Non Disclosure
Non Disclosure

Reputation: 33

jQuery .load() failure

I'm trying to run an answer I found at the following link: Asynchronously Load the Contents of a Div

But when I do, I get errors that I don't quite understand.

My code:

$(document).ready(function() {
  $("#first").load(function() {
    $("body").append($("<div></div>").attr({
      id: "second"
    }).text("Second"));
    $("#second").load(function() {
      $("body").append($("<div></div>").attr({
        id: "third"
      }).text("Third"));
    });
  });
});
<html>

<head>
  <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-
3.2.1.min.js"></script>
</head>

<body>
  <div id="#first">First</div>
</body>

</html>

The error I get back from Chrome is extensive. But here's the highlights:

Uncaught TypeError: a.indexOf is not a function
    at r.fn.init.r.fn.load (jquery-3.2.1.min.js:4)
    at HTMLDocument.<anonymous> (temp.html:6)
    at j (jquery-3.2.1.min.js:2)
    at k (jquery-3.2.1.min.js:2)

Any ideas?

Upvotes: 2

Views: 4813

Answers (2)

Jose Bibiloni
Jose Bibiloni

Reputation: 41

Your first issue is resolved by using:

$("#first").on('load', function() {
  *code to be executed*
}

.load has been deprecated since jQuery 1.8

The second issue you mention that only the first div is created happens because you are trying to execute the next function to create the third div when the second div is loaded but in reality the second div is not loaded since you are appending it so no load is occurring in this case.

You can just append one after the other and they will appear in order assuming that is what you are trying to do.

Upvotes: 0

Ankit Agarwal
Ankit Agarwal

Reputation: 30729

This error might be caused by jquery event aliases like .error, .load or .unload. These are deprecated since jQuery 1.8. You need to replace them with .on() to register listeners instead. Example:

$(window).load(function(){
  ...
});

becomes:

$(window).on('load', function(){
 ...
});

So try using with .on()

Upvotes: 9

Related Questions