0

How do I add extra parameters to a javascript event function? I want my current event functions to take in more parameters than just an event.

My current code is:

function getMousePos(canvas, evt) {
    var rect = canvas.getBoundingClientRect();
    return {
        x: (evt.clientX - rect.left) / (rect.right - rect.left) * canvas.width,
        y: (evt.clientY - rect.top) / (rect.bottom - rect.top) * canvas.height
    };
}

function give_mouse_coord(e) {
    var pos = getMousePos(canvas, e);
    
    var pos_x = pos.x
    var pos_y = pos.y
 }

window.addEventListener('click', give_mouse_coord, false);

but I want to have the give_mouse_coord take in other parameters as well, for example:

function give_mouse_coord(e, scalar) {
    var pos = getMousePos(canvas, e);
    
    var pos_x = pos.x * scalar
    var pos_y = pos.y * scalar
 }

I want the window.addEventListener to run my functions but when I try adding more parameters the function won't run.

1
  • 1
    You don't have to pass the name of a function to addEventListener. You can pass an anonymous function instead that does whatever, including calling other functions. What I'm saying is that you cannot change the fact that the JS engine only passes the event to the handler function but that doesn't mean you can't just do arbitrary stuff yourself, at any point. Commented Oct 6, 2021 at 18:23

1 Answer 1

3

Just wrap your handler function in an ad-hoc arrow func:

window.addEventListener('click', e => give_mouse_coord(e, whatever), false);
Sign up to request clarification or add additional context in comments.

1 Comment

I thought there's going to be a bunch of duplicates for sure but looking for them I found lots of really bad (and accepted) answers to this very same question. Couldn't find a dupe presenting this simple and obvious solution so I gave up :/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.