I Am Groot I Am Groot - 11 months ago 43
CSS Question

jquery fade in and out saving data chunk

I'm having some trouble with jQuery.

I have this code:

<div id="divSavingInformation" style="position:absolute;">All changes saved.</div>

$(document).on("blur","div[contenteditable=true]",function() {

var wait = Math.floor(Math.random() * 3000) + 500;

$('#divSavingInformation').fadeOut(500, function() {
$('#divSavingInformation').html("<i class='fa fa-spinner fa-pulse fa-lg fa-fw'></i> Saving data...").fadeIn(500).delay(5000).fadeOut(500).html("All data saved.").fadeIn(500);

var field_userid = $(this).attr("id") ;
var value = $(this).text() ;
$.post('pages/ajax/updateRadio.php' , field_userid + "=" + value, function(data){


The code is triggered via a contenteditable div.
here is a jsfiddle https://jsfiddle.net/oyv27cce/3/

Which doesn't work the way I need it to.
Basically, what I need it to do is this:

  1. Fade out div named "divSavingInformation"

  2. Change content of div to
    <i class='fa fa-spinner fa-pulse fa-lg fa-fw'></i> Saving data...

  3. fade in div to show the change above

  4. wait some seconds while showing the div, this will be a variable later, for now I'm using 5 seconds.

  5. fade div back out

  6. Change contents of div to
    All data saved

  7. fade back in and stay showing

Currently, what the code does is fade out and back in but the content doesn't appear to change. I think I am using delays wrong, maybe it is changing the content back to
All data saved
before it fades back in, making it look like the spinner is never shown.

I have no idea what I am doing, and could really use some help.

Answer Source

The issue is that fadeIn() and fadeOut() are asynchronous and they are queued up to perform the effect AFTER the currently running function completes. You will need to defer the final effect until after the function finishes and get rid of the delay() call as this will be taken care of by the setTimout():

$('#divSavingInformation').html("<i class='fa fa-spinner fa-pulse fa-lg fa-fw'></i> Saving data...</div>").fadeIn(500).fadeOut(5000);;

// Defer the following code until after this function has completed.

  $('#divSavingInformation').html('All data saved.').fadeIn(500);
}, 5000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divSavingInformation"></div>