Simple Doubt in Javascript

Asked

Viewed 60 times

3

Well my doubt is relatively simple, I would like to know how would do in Javascript that if a real condition, for example, 2 > 1 instead of 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">

  • That way you did it’s not working?

  • Unfortunately not.

  • Which error shows?

  • Still showing yellow image

  • Take a look at the browser console, which error shows?

  • Exactly, I had put this question first, but now that I’ve started to reason, I’ll try to make the colors appear in a row until I get that color.

  • Give me the error: http://prntscr.com/7hvwou

  • Click on that one teste.html:3 which is in the right corner, it will go straight to the line with error and sends a print dnv

  • Here you are: http://prntscr.com/7hvy1n

  • Although you have not shown the whole screen, can see that you are assigning in innerHTML and not in the src, Beyond that mistake I don’t know what else to not see until the end

  • I tried with src and Inner and both do not work.

  • In this example that is in your question is working normal, it must be some error that has been hidden, give an analysis.

  • I tried with src and it didn’t work either. http://prntscr.com/7hvz1r

Show 9 more comments

1 answer

4

The problem is that your script is running before the page is finished loading, so run only when finished do this:

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


Example changing the color of label every 5 seconds, adapt according to your needs. The function to keep calling every time is the setInterval and you report 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>

  • It worked, thank you very much! , By the way tell me one thing, if I want to make q after 5 seconds appear the orange image2 as I would? That’s how I would make another image appear after 5 seconds.

  • That is, wait 5 seconds, change color, wait another 5 change color dnv. etc...

  • @Gonçalo I changed my answer with an example for you, I didn’t do exactly what you need because I want you to understand and learn, but the idea is basically this.

  • Well, I etendi the idea, but in case I wanted to change the image, of different ids every 5 seconds, ie change the image id x, after 5 seconds change id y image. First of all thank you for this great help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.