Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top