Can someone help me change the image by using Javascript?

Asked

Viewed 61 times

4

I’m trying to change the image as the value of the variable in a change. For example, from 0 to 100 is an image, from 101 to 200 is another and so on.

I put any number from 0 to 100 and it returns me the image of the Indice 0, I put any number from 101 to 200 and returns me correctly the image of the Indice 1, but from 201 upwards the image does not change and continues to show the of the Indice 1.

var num = 568
var fotos = ["./img/Emblem_Iron.png", "./img/Emblem_Bronze.png", "./img/Emblem_Silver.png", "./img/Emblem_Gold.png", "./img/Emblem_Platinum.png", "./img/Emblem_Diamond.png", "./img/Emblem_Master.png", "./img/Emblem_Grandmaster.png", "./img/Emblem_Challenger.png"];
function alterarImagem() {
    if (num <= 100) {
        document.getElementById("img").src = fotos[0];
    } else if (num >= 101 || num <= 200) {
        document.getElementById("img").src = fotos[1];
    } else if (num >= 201 || num <= 300) {
        document.getElementById("img").src = fotos[2];
    } else if (num >= 301 || num <= 400) {
        document.getElementById("img").src = fotos[3];
    } else if (num >= 401 || num <= 500) {
        document.getElementById("img").src = fotos[4];
    } else if (num >= 501 || num <= 600) {
        document.getElementById("img").src = fotos[5];
    } else if (num >= 601 || num <= 700) {
        document.getElementById("img").src = fotos[6];
    } else if (num >= 701 || num <= 800) {
        document.getElementById("img").src = fotos[7];
    } else {
        document.getElementById("img").src = fotos[8];
    }
}

in html is like this

<img id="img" src="./img/Emblem_Iron.png" class="elo">
button id="btn" class="play" onclick="alterarImagem(400)">test</button>

2 answers

7

The problem there is you’re wearing one || (OR) instead of a && (And).

As 400 is greater than 101 soon condition:

if (num >= 101 || num <= 200)

is always true. If you change to

if (num >= 101 && num <= 200)

under the following conditions.

  • 1

    It worked! I’m new to javascript, I didn’t know much about these details! THANK YOU!

4

If you use || (or) as a condition, then it will not confirm the two conditions, because one of them is already satisfactory.

For example:

205 is over 100, so you don’t need me to confirm that it’s under 200, because:

OR is greater than 100, OR is less than 200. Understood?

Exchange the || for &&, that your problem solves.

Abs!

  • 1

    It worked! I’m new to javascript, I didn’t know much about these details! THANK YOU!

Browser other questions tagged

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