Having trouble retrieving data-attribute values from multiple divs with the same class when clicked. The goal is to display the data value of the clicked div.
function playSound(e) {
const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`);
const key = document.querySelector(`.key[data-key="${e.keyCode}"]`);
console.log(audio);
if (!audio) return;
audio.currentTime = 0;
audio.play();
key.classList.add('playing');
}
function removeTransition(e) {
if (e.propertyName !== 'transform') return;
this.classList.remove('playing');
}
const keys = document.querySelectorAll('.key');
keys.forEach(key => key.addEventListener('transitionend', removeTransition));
window.addEventListener("keydown", playSound);
const keysPressedMouse = document.querySelectorAll('.key');
keysPressedMouse.forEach(keyMouse => keyMouse.addEventListener('click',
playSoundMouse));
function playSoundMouse(e) {
const keyMouseSecond = document.querySelector(`.key[data-key="${e.keyMouse.}"]`)
console.log(keyMouseSecond);
}
https://codepen.io/hovsky/pen/dKQxBO
The keyboard functionality works, now trying to achieve the same effect by clicking different divs using the mouse. Instead of multiple functions, looking to consolidate everything into one function.
The keysPressedMouse function gathers all valid data-attributes into an object. However, the challenge lies in selecting the correct one. Currently, query selector only picks the first element, regardless of which div is clicked.
When checking console.log(e) in the playSoundMouse(e) function, it correctly displays the pressed DIV and identifies the correct data attribute https://i.sstatic.net/Ywkcc.png
Seeking guidance on how to extract and store the node value into a variable.
Thank you.