I have a code in which every time I press a button it shows me a random word from the list through a js code.
Now I want the word not to be displayed instantly, but to take a few seconds to display the word and while those seconds pass, a loading gif image is displayed . When those seconds are over, the image changes and one is shown, for example, YOU ARE FINISHED!.
How do I program that delay in displaying the information?
HTML
<!-- Gif mientras carga -->
<div id="cocinando">
<img src="images/cocinando.gif" alt="cocinando" title="Cocinando"/>
<p>cocinando</p>
</div>
<!-- Muestra la palabra aleatoria -->
<div class="word">
<span id="wordOutput"></span>
</div>
<button id="randomWordGen">Generate</button>
JS
document.addEventListener('DOMContentLoaded', function () {
var clickTimes = 0;
var btnRandomWord = document.getElementById('randomWordGen');
var wordOutput = document.getElementById('wordOutput');
btnRandomWord.addEventListener('click', function () {
if (clickTimes < 3) {
var request = new XMLHttpRequest();
// método HTTP y URL
request.open('GET', 'randomwordgen.php');
request.onload = function () {
// estado 4 = petición completada y respuesta recibida
if (request.readyState === 4) {
// código HTTP 200 = petición exitosa
if (request.status === 200) {
wordOutput.textContent = request.responseText;
clickTimes++;
}
}
};
request.send(); // se envía la petición
} else {
wordOutput.textContent = 'PALABRA FINAL';
}
});
});
In the click event of the button that makes the AJAX request, you must display the gif. Then, when the word is received from the server, you define a timeout with the seconds you want. When the timeout runs, you output the load image.
In your CSS add a couple of rules: