Jquery Animate overlapping on Loading Image

135 views Asked by At

I am working on a project in which the navigation does not really changes pages but gets data using services based on which navigation link I click and update data using jquery .html() method, I want to use a loader that shows up on clicking any link and hides the content, when ajax services is successfull i want to remove the loader and show back the content, but somehow the animations are overlapping causing animations to fail,

in example code here i am not using ajax to update my page but a simple button and jquery to update the data

        <body>

        <div id="loader">
            <img src="loader.gif" alt="">
        </div>

        <br>

        <div id="content">
            This is the content
        </div>

        <input type="button" id="update" value="Update Data">




    </body>

        <script>

        function showContent(){
      $('#loader').fadeOut(200).promise().done(function(){
           $('#content').fadeIn(200).promise().done(function(){
           });
      });
    }


    function hideContent(){
        $('#content').fadeOut(200).promise().done(function(){
           $('#loader').fadeIn(200).promise().done(function(){
           });
        });
    }

$("#update").click(function(){
    hideContent();
    $("#content").html("New Data");
    setTimeout(showContent(), 10000);

});



        </script>

on clicking update, this should happen content should disappear, loader should appear, update content, loader disappear, content appear,

but i get both loader and content appeared in the end

I used setTimeout to give some delay but it doesnt works , i also used some flags earlier but that didnt work too . JsFiddle : JsFiddleLink

1

There are 1 answers

0
guest271314 On

Why use setTimeout()? You can return, chain the promise

function showContent(){
  return $('#loader').fadeOut(200).promise().done(function(){
       return $('#content').html(data).fadeIn(200).promise()
  });
}


function hideContent(){
    return $('#content').fadeOut(200)
    .done(function() {
       this.empty();
       return $('#loader').fadeIn(200).promise()
    });
}

$("#update").click(function() {
  hideContent().then(showContent)
})