Problem with Javascript Image Exchange for User Interaction

Asked

Viewed 5,288 times

1

I am developing a code for user interaction, in which it should light a lamp when passing the mouse over, and break it case click about her.

The iteration of hover is occurring normally, but click does not work in the IE, Chrome.

Anyone can help?

function MudaLampada(tipo) {
  if (tipo == 1) {
    arquivo = "http://i.stack.imgur.com/ybxlO.jpg";
  }
  if (tipo == 2) {
    arquivo = "http://i.stack.imgur.com/ybxlO.jpg";
  }
  if (tipo == 3) {
    arquivo = "http://i.stack.imgur.com/MRjsF.jpg";
  }
  document.getElementById("luz").src = arquivo;
}
<!DOCTYPE html>
    <html lang="pt-br">

    <head>
      <meta charset="UTF-8">
      <title>Teste Javascript</title>
      <script>
        function MudaLampada(tipo) {
          if (tipo == 1) {
            arquivo = "_imagens/lampada-acesa.jpg";
          }
          if (tipo == 2) {
            arquivo = "_imagens/lampada-apagada.jpg";
          }
          if (tipo == 3) {
            arquivo = "_imagens/lampada-quebrada.jpg";
          }
          document.getElementById("luz").src = arquivo;
        }
      </script>
    </head>

    <body>
      <h1>Acenda a Lampada</h1>
      <img src="_imagens/lampada-apagada.jpg" id="luz" onmousemove="MudaLampada(1)" onmouseout="MudaLampada(2)" onclick="MudaLampada(3)" />
    </body>

    </html>

Lampada Apagada Lampada Quebrada Lampada Acesa

  • Which version of IE does not work?

  • In IE it is working just not in others but it gives a certain bug in IE tbm

4 answers

3

The problem is that the "onclick" event fires along with "onmousemove". Would need to add some logic to avoid calling Lamp change (1) after someone calls Lamp change(3).

1

I believe the problem is caused by mousemove after clicking on the image, as pointed out by Fabricio.

An alternative is to use CSS to toggle the images of the lamp on/off with the basic event of :hover. And then use Javascript only to insert a class responsible for changing the image and show the broken lamp in the event click, for example:

/**
 * Quando clicado, adicionará a classe 'broken' (caso ela não esteja
 * presente), do contrário ela será removida.
 **/
document.querySelector('.lamp').addEventListener('click', function(){
    this.classList.toggle('broken');
}, false);
.lamp {
    height: 220px;
    width:  169px;
    background-image: url(http://i.stack.imgur.com/b983w.jpg); /* apagada */
    background-repeat: no-repeat
}

.lamp:hover {
    background-image: url(http://i.stack.imgur.com/ybxlO.jpg)  /* acesa */
}

.lamp.broken {
    background-image: url(http://i.stack.imgur.com/MRjsF.jpg)  /* quebrada */
}
<h1>Acenda a lampada</h1>
<div class='lamp'></div>

Remembering that not all browsers support classlist, how can it be seen on that link. But in that reply there are some ways to manipulate classes in an element.

1

The logic you lack is that when the bulb breaks it no longer makes sense to use the mousemove. In fact mousemove is the wrong event for it because it shoots too many times, you just need to know whether it’s on top of the element or not.

I suggest you use mouseenter and mouseleave, and change the logic to:

HTML

<img src="http://i.stack.imgur.com/b983w.jpg" id="luz" />

Javascript

(function(){

    var inteira = true;
    var img = document.getElementById("luz");
    var estado = {
        click: 'http://i.stack.imgur.com/MRjsF.jpg',
        mouseenter: 'http://i.stack.imgur.com/ybxlO.jpg',
        mouseleave: 'http://i.stack.imgur.com/b983w.jpg'
    };

    img.addEventListener('click', mudaLampada);
    img.addEventListener('mouseenter', mudaLampada);
    img.addEventListener('mouseleave', mudaLampada);

    function mudaLampada(evento) {
        if (!inteira) return; // se já estiver partida nõ fazer nada
        if (evento.type == 'click') inteira = false; // marcar como partida
        img.src = estado[evento.type];
    }

})();

jsFiddle: http://jsfiddle.net/mL6c9y7r/

-1

/*Cara o seu foi colocar essas chave dentro da function, olha o seu erro:*/



 if (tipo == 1) {
            arquivo = "_imagens/lampada-acesa.jpg";
          }
          if (tipo == 2) {
            arquivo = "_imagens/lampada-apagada.jpg";
          }
          if (tipo == 3) {
            arquivo = "_imagens/lampada-quebrada.jpg";
          }


/*Dentro função, você abriu e fechou chave, essa: {}
esse foi o seu erro, o código é executado dentro da função, então deve ser escrito da seguinte forma:*/

if (tipo == 1) 
arquivo = "_imagens/lampada-acesa.jpg";
if (tipo == 2) 
arquivo = "_imagens/lampada-apagada.jpg";
if (tipo == 3) 
arquivo = "_imagens/lampada-quebrada.jpg";


/*Pois você está executando um comando dentro de uma função, então seu código deve ficar assim:*/
<!DOCTYPE html>
<html>
<head>

<title>Teste Javascript</title>
<meta charset="UTF-8">

<script>
var quebrada = false;
function mudaLampada(tipo) {
if (tipo == 1) 
arquivo = "_imagens/lampada-acesa.jpg";
if (tipo == 2) 
arquivo = "_imagens/lampada-apagada.jpg";
if (tipo == 3) 
arquivo = "_imagens/lampada-quebrada.jpg";
if (!quebrada)
document.getElementById("luz").src = arquivo;
if (tipo == 3) 
quebrada = true;
}
</script>
</head>
<body>
<h1>Acenda a lâmpada</h1>
<img src="_imagens/lampada-apagada.jpg" id="luz" onmousemove="mudaLampada(1)" onmouseout="mudaLampada(2)" onclick="mudaLampada(3)"/>
</body>
<html>

Browser other questions tagged

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