How to exchange images in javascript and Html5?

Asked

Viewed 7,626 times

0

I’m building a mobile application that detects beacons when activating mobile bluetooth, using Evothings, which uses javascript and Html5. Once I detect the beacons, I need one image to change to make room for the other. Testing by codepen the code works, but when I test in the application, nothing happens and the image does not change.

HTML

"<html>
<body>
<img id="teste" src="http://db13.in/wp-content/uploads/2016/07/2000px-Dialog-error-round.svg_.png" width="160" height="120" onLoad="trocaImg(int);">
</body>
</html>"

JAVASCRIPT

var int = 2;
var img = document.getElementById("teste");
function trocaImg(int){
  if (int == 1)
    {
      img.src = "http://db13.in/wp-content/uploads/2016/07/2000px-Dialog-error-round.svg_.png";
    }
  else if (int == 2)
    {
      img.src = "https://t3.ftcdn.net/jpg/01/45/20/02/160_F_145200260_Mlts2v0PtYabB4v5dz1I8hKNCfieJidW.jpg";
    }
}

1 answer

1

Try changing the name of the int variable, since it is a reserved Javascript word. There is also no need to pass a parameter to the function, since the variable int was globally declared

var num = 2;
var img = document.getElementById("teste");
function trocaImg(){
//apenas para cunho de testes
setTimeout(function () {
  if (num == 1)
    {
      img.src = "http://db13.in/wp-content/uploads/2016/07/2000px-Dialog-error-round.svg_.png";
    }
  else if (num == 2)
    {
      img.src = "https://t3.ftcdn.net/jpg/01/45/20/02/160_F_145200260_Mlts2v0PtYabB4v5dz1I8hKNCfieJidW.jpg";
    }
    //garante que num fique alternando entre 1 e 2
    num = (num % 2) + 1;
    }, 1000);
}
<html>
<body>
<img id="teste" src="http://db13.in/wp-content/uploads/2016/07/2000px-Dialog-error-round.svg_.png" width="160" height="120" onLoad="trocaImg();">
</body>
</html>

Browser other questions tagged

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