JQuery fadeIn () fires twice

I load html content via ajax on click event. My code is

$.ajax({
  url: somelink,
  async: true,
  beforeSend: function () {
      $("#myDiv").fadeOut("slow");
      $("#myDiv").empty();
  },
  success: function (data) {
      $('#myDiv').html(data);
      $("#myDiv").fadeIn("slow");
  },
  error: function (request, status, error) {
     alert("Error");
  },
  complete: function () {
  }
 });

Problem: #myDiv freezes twice. What is the problem?

+3
source share
1 answer

It seems to be related to the html () call, which actually shows the content very quickly, and then hides it again before fadeIn starts working. If the content is not updated, fadeIn / out behaves as expected.

You can use .hide () in the success function:

beforeSend: function () {
    $("#myDiv").fadeOut("slow").empty();
},
success: function (data) {
    $('#myDiv').hide().html("test!").fadeIn("slow");
},
+3
source

All Articles