Simple Javascript Debugging

3

Well my question is relatively simple, I would like to know how I would do in Javascript that if a true condition, for example, 2 > 1 instead of appearing the image of img appeared the image of the code in script .

My code:

if(2>1){ document.getElementById("amarelo5").src = "cores-roleta/amarelo1.png";

}
<img id="amarelo5" src="cores-roleta/amarelo0.png">
    
asked by anonymous 17.06.2015 / 05:46

1 answer

4

The problem is that your script is running before the page finishes loading, to run only when it's finished do this:

window.onload = function() {
    if(2>1){ 
        document.getElementById("amarelo5").src = "cores-roleta/amarelo1.png";
    }
}


Example changing the% color of% every 5 seconds, adapt as needed. The function to be calling at each time is label and you inform in milliseconds.

var cores = ['red', 'blue', 'green'];
var contador = 0;
window.onload = function() {
    setInterval(function () {
        document.getElementById('tst').style.color = cores[contador % cores.length];
        contador++;
    }, 5000); // 5 segundos
}
<label id="tst">Exemplo cores</label>
    
17.06.2015 / 06:29