How to swap images in javascript and html5?

0

I am putting together a mobile app that detects beacons when activating the bluetooth of the phone, using Evothings, which uses javascript and html5. When I detect the beacons, I need one image to change to give way to 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";
    }
}
    
asked by anonymous 22.09.2017 / 15:18

1 answer

1

Try changing the name of the int variable, since it is a JavaScript reserved word. There is also no need to pass a parameter to the function since the int variable 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>
    
22.09.2017 / 15:29