A mouse event should call one of two functions, depending on the condition flag = 0, or flag = 1. How to redefine the flag variable, so that one or the other function would work, depending on the value of this variable. Tried it in many different ways. Nothing comes out.

<script type="text/javascript"> flag=0; window.onload = function() { canvas = document.getElementById("Canva"); context = canvas.getContext("2d"); canvas.onmousedown = show; if(flag == 0) { canvas.onmousdown = show;} else if(flag == 1) {canvas.onmousdown = show2;} } function show() { alert('Next'); } function show2() { alert('Stop'); } </script> 

You can set if else and in the condition of calling the alerts in the function itself. But the essence does not change, the override variable flag does not work out.

    1 answer 1

    1. At the first mention (declaration) of a variable, use var .
    2. You did not correctly set the click event handler for the canvas, see an example of how it is correct:

     var flag = 0; window.onload = function() { canvas = document.getElementById("Canva"); context = canvas.getContext("2d"); canvas.addEventListener("mousedown", function() { if(flag == 0) { flag = 1; show(); } else { flag = 0; show2(); } }, false); } function show() { alert('Next'); } function show2() { alert('Stop'); } 
     #Canva { border: 1px solid red; } 
     <canvas id="Canva"></canvas> 

    • If replaced by onmousedown - does not work. I generally need to process onmousemove. I am in this example, much simplified for readability. - Dima
    • The addEventListener must be used without on. If you need onmousemove - register mousemove . - ikerya
    • If you set mousemove instead of onmosemove, the code stops working. - Dima
    • paste your code on pastebin.com and provide a link - ikerya