Problems with onmouseclick and onmouseover in Javascript

Asked

Viewed 574 times

4

I have the following code:

Javascript test

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

<body>
    <h1>Acenda Lampada</h1>
    <img src="_imagens/lampada-apagada.jpg" id="luz"  onmouseover="mudaLampada(1)" onmouseout="mudaLampada(2)" onmouseclick="mudaLampada(3)">
</body>

The function works for type 1 and 2, but for type 3 nothing happens; can anyone find the error? Thanks.

  • 1

    Welcome to Stackoverflow English, take a tour to learn more about Sopt: https://answall.com/tour

2 answers

6


Uses the attribute onclick and not onmouseclick. Notice that when you click and raise the mouse it will immediately pass to the state onmouseover.

To fix it or use the onmouseenter (example) or creates a logic like this:

var partida = false;

function mudaLampada(tipo) {
    if (partida) return;
    if (tipo == 1) {
        arquivo = "_imagens/lampada-acesa.jpg";
    } else if (tipo == 2) {
        arquivo = "_imagens/lampada-apagada.jpg";
    } else if (tipo == 3) {
        arquivo = "_imagens/lampada-quebrada.jpg";
        partida = true;
    }
    document.getElementById("estado").innerHTML = arquivo;
}

jsFiddle: https://jsfiddle.net/xLevgan3/

1

Change onMouseClick to onClick.

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

Browser other questions tagged

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