HovSky
HovSky

Reputation: 49

JavaScript get data-attribute multiple divs

I have a problem with multiple divs and getting their data-attribute values. All divs have the same class, and depending on which one I clicked, it should display that data-attribute value.

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

It works with keyboard, now I want the same effect with mouse clicking on different divs. I know there is the easy solution to use "onclick=function(this)", but I'm trying to avoid using multiple functions, and try to put them all under the same function.

the keypressedMouse selects all valid data-attributes and puts them into an object, but now I have a problem how to select the real one. Unfortunately, query selector selects the first element, so whatever div I press, only the first one is selected.

console.log(e) in playSoundMouse(e) function, display the correct DIV that is pressed and I can find the correct data attribute correctly displayed div with a node value that is needed

How can I access that node value and store it into a variable?

Thank you.

Upvotes: 1

Views: 1231

Answers (1)

Barmar
Barmar

Reputation: 781120

You should split up playSound() into two function -- one that deals with the keyboard event, and one that just plays the sound. Then you can call that second function from the function that handles mouse events as well, since the two events look up the parameters differently.

function playSound(keyCode) {
  const audio = document.querySelector(`audio[data-key="${keyCode}"]`);
  const key = document.querySelector(`.key[data-key="${keyCode}"]`);
  console.log(audio);
  if (!audio) return;
  audio.currentTime = 0;
  audio.play();
  key.classList.add('playing');
}

function playSoundKbd(e) {
  playSound(e.keyCode);
}

document.querySelectorAll("div.key[data-key]").forEach(d => d.addEventListener("click", playSoundMouse));

function playSoundMouse(e) {
  playSound(e.currentTarget.dataset.key);
}

Upvotes: 1

Related Questions