1

Why does the code at this JS fiddle not work? I want it to log a blank string, but it's logging a Pointer Event. https://jsfiddle.net/wvom7k2f/

let c = document.getElementById('c');
c.onclick = test;

function test(a='', b=''){
console.log(a);
}
1
  • 1
    the first parameter to all events is the Event object itself Commented Feb 11, 2022 at 17:19

2 Answers 2

4

An onclick event handler will put the event as the first parameter. If you want to call test with no parameters you should change c.onclick = test; to the following:

c.onclick = () => test();
Sign up to request clarification or add additional context in comments.

7 Comments

@maksymiuk That’s what the default parameters in the question are for.
@maksymiuk - By assigning a function to onclick that, when called, will call test with no arguments, triggering the default parameter value (which is a blank string).
His test function will do that.
@T.J.Crowder I stand corrected, I somehow misinterpreted the code, and I retract my dislike
@maksymiuk - We've all done that kind of thing. :-) (You can remove the comment, too, if you like.)
|
3

You're doing c.onclick = test. The onclick event calls its function with the event as the 1st parameter.

Try to do:

function test(e, a='', b='') {
    console.log(a);
}

c.onclick = test;

Or, if you don't want to change test(), then you can do:

function test(a='', b='') {
    console.log(a);
}

c.onclick = function(e) {
    test();
};

3 Comments

Makes sense. So what would be the proper way to do it if I want to also call that function elsewhere, such as test('foo', 'bar')?
@user568551 I added a 2nd block of code. You could do c.onclick = function() { test(); }.

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.