Frage

I drew a canvas, and then with the code

canvas.addEventListener("mousedown", clicked(event), false);

I added an event listener to run clicked whenever I click the mouse. But when I went through the code line by line on chrome, the moment it adds the event listener it automatically runs the function clicked anyway, but I only want it to run the function when I click.

Am I doing something wrong?

War es hilfreich?

Lösung

You need to just pass the function reference and not actually call it like this:

canvas.addEventListener("mousedown", clicked, false);

Then, the function should be defined like this:

function clicked(event) {
    // code here
}

When you include parens after the function name, it is immediately executed and it's return value is what is passed to addEventListener() which is probably not what you wanted at all. Leave off the parens to just pass a function reference.

Andere Tipps

canvas.addEventListener("mousedown", clicked,false);

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top