Hello, I am hitting a roadblock with the Piano Keys project. According to the AI assistant, and referencing the walkthrough video, my code through Task 6 should function correctly:
// The keys and notes variables store the piano keys
const keys = ['c-key', 'd-key', 'e-key', 'f-key', 'g-key', 'a-key', 'b-key', 'high-c-key', 'c-sharp-key', 'd-sharp-key', 'f-sharp-key', 'g-sharp-key', 'a-sharp-key'];
const notes = [];
keys.forEach(function(key){
notes.push(document.getElementById(key));
})
// Write named functions that change the color of the keys below
const keyPlay = function(event) {
event.target.style.backgroundColor = 'lightorange';
}
const keyReturn = function(event) {
event.target.style.backgroundColor = '';
}
// Write a named function with event handler properties
const keyChange = function(note) {
note.onmousedown = function(event) {
keyPlay(event);
}
note.onmouseup = function(event) {
keyReturn(event);
}
}
// Write a loop that runs the array elements through the function
notes.forEach(keyChange);
However, this error consistently arises regardless:
/home/ccuser/workspace/dom-events-piano-keys/main.js:5
notes.push(document.getElementById(key));
^
ReferenceError: document is not defined
at /home/ccuser/workspace/dom-events-piano-keys/main.js:5:14
at Array.forEach (native)
at Object.<anonymous> (/home/ccuser/workspace/dom-events-piano-keys/main.js:4:6)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:427:7)
The Learning Assistant gives the following explanation:
It seems you are encountering a
ReferenceErrorbecause the code is attempting to use
documentin a Node.js environment where
documentis not defined since it’s specific to web browsers. To fix this error, you should adjust your code to run in a browser environment, not in a Node.js environment. Since
document is not available in Node.js, you would need to run this code in an HTML file with appropriate script tags.
I have no reason to believe the code provided when starting the project is incorrect, and the script element is at the bottom of the html body sourcing ‘main.js’.
This error has been persisting throughout the lessons in the ‘Building Interactive JavaScript Websites’ skill path course, but this is the first time events haven’t triggered.