I am trying to display text on a website that comes from a json file. When the data in the json file changes, the text should fade out, change to the new value and then fade back in. I have struggled to get this to work, in the code below, the data initially displays, fades out, and then fades in. I am not sure why the text is displayed initially. I would think the current div would fade out, the data would be added to the div, and then fade in, without seeing the extra step of initially being displayed before fading out. The result is not a smooth transition between changes in data. I am sorry, but what am I missing here?
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">.</script>
</head>
<body style="background:#000000;">
<script>
var currentText;
setInterval(function checkUpdate()
{
$.ajaxSetup({ cache: false });
$.ajax({
type:"get",
cache: false,
url: 'temp.json',
success:function(data) {
var textSource = data.currentText[0].text;
if(currentText !== textSource) {
$("#dataDiv").fadeOut(2000);
$("#dataDiv").html('<h1><font color=#ffffff>' + textSource + '</font></h1>')
//.fadeOut(2000)
.fadeIn(2000);
}
currentText = textSource;
}
});
return checkUpdate;
}(), 5000);//time in milliseconds
</script>
<div style="background:#000000"><div id="dataDiv"></div></div>
</body>
</html>
The json file:
{
"currentText": {
"0": {
"id": "1",
"text": "This is a test again."
}
}
}
You need to use the callback function
https://api.jquery.com/fadein/
$("div#test").fadeOut(2000, function(){
$(this).html('<h1><font color=#ffffff>Test</font></h1>').fadeIn(2000);
});
h1 { background-color:#000 }
div { font-size:2em }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test">Test</div>