Problem with Image Interchange by User Interaction in Javascript

1

I am developing a code for user interaction, in which he should light a lamp by hovering his mouse over it, and break it down with click on it.

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

Can anyone 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>

    
asked by anonymous 10.09.2015 / 21:53

4 answers

3

The problem is that the "onclick" event fires together with "onmousemove". You would need to add some logic to avoid calling Callback (1) after someone calls Callback .

    
12.09.2015 / 00:57
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 of 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 , such as seen on this link . But in this answer (en) there are some ways to manipulate classes in an element.

    
12.09.2015 / 02:07
1

The logic you're missing is that when the bulb starts it does not make sense to use mousemove . In fact mousemove is the wrong event for this because it shoots too many times, you just need to know if it's on top of the element or not.

I want to use mouseenter and mouseleave , and change 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: link

    
12.09.2015 / 07:21
-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>
    
05.10.2018 / 02:03