Function with event handler properties - piano keys project

I’m working on the “Piano keys” project (https://www.codecademy.com/paths/web-development/tracks/build-interactive-websites/modules/dom-javascript-events/projects/piano-keys) and the thing I don’t understand is about the syntax of the first function with event handler properties that we are asked to write.

We are first asked to write a function that changes the color of the keys, and I wrote:
const keyPlay = function(event) {
event.target.style.backgroundColor = ‘yellow’;
}

Later we are asked to write a function (which I called playNote) that runs the keyPlay function when a mousedown event fires on a note. I would have written this:

let playNote = function(note) {
note.onmousedown = keyPlay(event);
}

but the “walkthrough video” tells us instead to do it like this:

let playNote = function(note) {
note.onmousedown = function(event) {
keyPlay(event);
}
}

Why is the redundancy necessary? can’t I just say note.onmousedown = playNote(event) but must instead call another anonymous function (note.onmousedown = function(event) {keyPlay(event)})?

True, but in the event that you may want to call for another function on the same onmousedown action you can add it to the code inside the anonymous function saving you time and code lines.

Its just a trick they are teaching you might not have thought of before, but it is very good of you to think it through like this! :smiley:

1 Like

Ok, that makes sense. Thank you!

1 Like