0

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

UmeRonaldo
  • 619
  • 2
  • 7
  • 19
  • 1
    For starters, you pass a function reference to `setTimeout()` like this: `setTimeout(showContent, 10000);`, not like this `setTimeout(showContent(), 10000);` When you put `()` after the function name that means to execute it immediately and then pass the return result from the function to `setTimeout()` which is not what you want. But, really you shouldn't be using timers at all. You should be using the completion of the loading event to trigger the change. – jfriend00 Jul 27 '16 at 00:11
  • :O i should have seen this before, yes it working now but its not what i should use, thank u – UmeRonaldo Jul 27 '16 at 00:16

1 Answers1

0

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)
})
guest271314
  • 1
  • 15
  • 104
  • 177