I'm using fetch API to access a JSON-object.
My questions is how can I implement a CSS loader before the actual data is displayed, and how do I know that the data has been displayed.
This is what I've tried:
var startSevenDaysInterval = (new Date).getTime();
var endSevenDaysInterval = startSevenDaysInterval - 604800000;
function fetchData2() {
fetch('https://vannovervakning.com/api/v1/measurements/3/' + endSevenDaysInterval + '/' + startSevenDaysInterval + '/')
.then(function (response) {
if(response === 404){
document.getElementById("loader").style.display = 'none';
}
return response.json();
})
.then(function (data) {
document.getElementById("loader").style.display = 'none';
printTemperature(data);
});
}
function printTemperature(data) {
var html = "<h5>";
html += data.data["TEMPERATURE"][0].value;
html += "</h5>";
document.getElementById('temp1').innerHTML = html;
}
setInterval(function () {
fetchData2();
}, 1000);
My loader looks like this:
.loader {
border: 4px solid #f3f3f3; /* Light grey */
border-top: 4px solid #e0e0e0;
border-radius: 30px;
width: 30px;
height: 30px;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
And my HTML looks like this:
<div class="tempVal">
<div class="loader"></div>
<div id="temp1"></div>
</div>
You are already doing that, but using getElementById
for a class (it's for IDs only). When you're not sure about these things make sure you have actually got the element you want e.g. using a debugger
statement or console.log(document.getElementById("loader"))
.
Get a class with querySelector
which can handle all css selectors:
document.querySelector('.loader').style.display = 'none'
Note if you have multiple classes with that name it will get the first one. You don't need to repeat it in both .then
's.