Given the following code , which is intended to be a minigame about matching a number in a given range from zero to x with a given number of guesses:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Ejercicio 3</title>
</head>
<body>
<table width="25%" border="0">
<tr>
<td>
<label for="textfield_1">Orientación:</label>
<input type="text" name="textfield_1" id="mensaje" />
</td>
<td>
<label for="textfield_2">Intentos restantes:</label>
<input type="text" name="textfield_2" id="intentos" />
</td>
</tr>
</table>
<script>
var max = prompt("Introduzca el número máximo que desea para el rango de búsqueda");
var num1 = Math.round(Math.random()*max); //Número objetivo
var num2; //Número del usuario
var count = prompt("¿Cuántos intentos desea tener?");
var mensaje = document.getElementById("mensaje");
var intentos = document.getElementById("intentos");
do{
num2 = prompt("Introduzca un número");
if(num1 < num2) mensaje.value="Más bajo";
if(num1 > num2) mensaje.value="Más alto";
if(num1 == num2) mensaje.value="¡ACERTASTE!";
count--;
intentos.value = count;
}while(num1 != num2 && count != 0);
if(num1 != num2) mensaje.value="Sin intentos: otra vez será";
</script>
</body>
</html>
You can see that the table is before the script, but it is not displayed on the page until the script has finished . In this way, it deprives the player of orientation information and attempts.
As far as I understand, the reading of the code is linear, which implies that the table should appear before the script and it should be updated as each round is played.
So what have I done wrong? Thanks.
The table is shown before, but in the script you have some prompts that jump immediately so you have the impression that the script happens first, but it doesn't.
Regardless, it's always a good idea to put JavaScript code that is going to interact with DOM elements inside a listener
DOMContentLoaded
, which will ensure that the DOM is loaded before the JavaScript code tries to use any of its components.And, if you want the prompts to not be launched like now, launch them from an action, like pressing a button or something.
Anyway, to prove to you that I'm not lying, I'm going to add a test
td
with a value2
and I'm going to show it at the prompt. You will see the value2
displayed, a sign that the table is loaded when the prompt occurs.