I have this code in which when clicking a button a window opens and a counter appears that is a random number between 1 and 100, this counts up to 0 and the window closes, but I don't know very well what I'm doing wrong since nothing appears in the window that I open. Here I leave part of the html code because I decide to open it by giving a button and the javascript.
var ventana;
function abrir() {
ventana = window.open("", "new_window", "width=800,height=500,status=no,toolbar=no,menubar=no");
}
window.onload = contar;
function contar() {
var contartiempo = Math.floor(Math.random() * 100);
ventana.document.getElementById('contador').innerHTML = contartiempo;
if (contartiempo == 0) {
ventana.close();
}
ventana.document.write(" tu contador:<span id = contador></span>") //quiero que se muestre en la ventana abierta el contador
}
<body>
<input type="submit" value="Abrir" onclick="abrir()">
</body>
I have already solved my problem, the code shows a window, performs the counter and closes that window, here the result
var ventana;
function abrir() {
ventana = window.open("", "new_window", "width=800,height=500,status=no,toolbar=no,menubar=no");
contar()
}
window.onload = contar//para que cuando
var contartiempo = Math.floor(Math.random() * 100);
function contar() {
if (ventana) {
ventana.document.write(" <span id = contador></span>") //quiero que se muestre en la ventana abierta el contador
ventana.document.getElementById('contador').innerHTML = contartiempo;
if (contartiempo == 0) {
ventana.close();
} else{
contartiempo-=1;
setTimeout("contar()",1000);
}
}
}
So, there are a lot of concern in this code:
You're loading contar function on load and till that time ventana is undefined hence you'll get an error when you do something like ventana.whatever (trying to access a property on undefined).
Since the document in the new page has no span with id = contador when created, the line ventana.document.getElementById('contador').innerHTML = contartiempo; will also fail.
To fix it:
var ventana;
function abrir() {
ventana = window.open("", "new_window", "width=800,height=500,status=no,toolbar=no,menubar=no");
contar()
}
function contar() {
if (ventana) {
var contartiempo = Math.floor(Math.random() * 100);
ventana.document.write(" tu contador:<span id = contador></span>") //quiero que se muestre en la ventana abierta el contador
ventana.document.getElementById('contador').innerHTML = contartiempo;
if (contartiempo == 0) {
ventana.close();
}
}
}
Here I am calling contar function on click of the button in parent document after we have opened the new window. Then I am putting the span & the other layout on the page with ventana.document.write. Then we are adding an innerHTML to that span.
HTML part will require no changes.