Piano Keys Project

Why doesn’t my function change the color of the keys?

let changeKeyColor = document.getElementById('key');
 function keyPlay(){
   changeKeyColor.target.style.backgroundColor = "blue";
}
changeKeyColor.addEventListener('keydown', keyPlay);

Hey @tag9677509016

either you style target or changeKeyColor.
If you put a console.log(changeKeyColor.target) into your function, what does it say?

Thanks for the quick reply but unfortunately nothing happens.

Ok, I guess your html item ‘key’ doesn’t accept a ‘keydown’ event. So for debugging purposes replace the ‘keydown’ by ‘click’, add a button with the ID and see what your console logs when you click the item.

It worked. Thanks for your help I really do appreciate it. I think my problem was that I didn’t understand how target should be used and if style can be used in conjunction with it.

1 Like

Hey friend here I am getting an error message in the last line of these bunch of code. Can anyone please help me? Console in the chrome browser throw me an error message that “references error keyNotes is not defined”

//dom using class name from html
const keys = [’.c-key’, ‘.d-key’, ‘.e-key’, ‘.f-key’, ‘.g-key’, ‘.a-key’, ‘.b-key’, ‘.c2-key’, ‘.c-sharp-key’, ‘.d-sharp-key’, ‘.f-sharp-key’, ‘.g-sharp-key’, ‘.a-sharp-key’];

const keyNotes = ;

//for each loop to take the target dom

keys.forEach(function(keys) {

keyNotes.push(document.querySelector(keys));

});

//named function that change the color of the target key

const keyColor = function(event) {

event.target.style.backgroundColor = '#b3ff1a';

};

const keyReturn = function(event) {

    event.target.style.backgroundColor = '';

}

//function handler event listener;

const eventAssignment = function(keynote) {

keynote.addEventListener('mousedown', keyColor);

keynote.addEventListener('mouseup', keyReturn);

};

//run array element through for each loop

KeyNotes.forEach(eventAssignment);

Hi @rkprite09
‘keys’ is the name of your array, not a DOM node. That doesn’t work. Also there’s not much sense in pushing a whole array.

I am new in javascript. I can’t solve it. Please instruct me how to do that. Please.