Access information from multiple div elements using JavaScript data-attributes

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.

Answer №1

If you divide the playSound() function into two separate functions – one to handle keyboard events and another to simply play the sound – you can then call the second function from the mouse event handler as well. This is because the two events require different parameter lookups.

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);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to modify variable values in AngularJS

I'm currently utilizing AngularJS along with the "Angular Material" implementation (found here: https://material.angularjs.org/latest/#/) One of the components I'm using is the SideNav component: https://material.angularjs.org/latest/#/demo/mate ...

When using Promise.all(), it surprisingly gives back an array of Promise <Pending>'s that are undefined, even though other solutions produce successful results

Currently, I am in the process of developing a web application that enables users to access a dashboard displaying various items. Each item comprises sections labeled as a, b, and c, which are represented as complete (o) or incomplete (x) on the dashboard. ...

Avoiding overlapping in setTimeOut when using jQuery.hover()

Looking to trigger an effect one second after the page loads, and then every 3 seconds in a loop. When the user hovers over a specific element with the ID #hover, the effect should pause momentarily. It should then resume 2 seconds after the user stops hov ...

What could be the reason that the Mui button styles are not being applied even after setting it to 'contained'?

Upon updating to the most recent version of MUI, I've noticed a problem with MUI buttons when using the contained variant. <div className="flex"> <Button variant="contained" color="primary" fullWidt ...

"Encountering a problem with a function showing an undefined error

Trying to incorporate a slider feature into my application led me to reference this w3schools sample. However, upon loading the page, the images briefly appear before disappearing. Additionally, clicking on the arrow or dots triggers an error stating: U ...

Error in background request for Chrome app/extension, or problem allowing app to access Google Docs API

I'm encountering an issue where the Google Doc API is not allowing a desktop application to be installed, although this worked fine in Chrome 27.0 previously. Below is my Manifest.Json file: { "name": "__MSG_extName__", "description": "__MSG_ext ...

A guide to resolving the error "Unable to find 'require' in vuejs"

I am currently working on a project using vuejs and firebase. I encountered an issue while trying to import firestore. When I accessed my page, I saw this error message in the console: ReferenceError: require is not defined I attempted to place the import ...

"Error: imports are undefined" in the template for HTML5 boilerplate

After setting up an HTML5 Boilerplate project in WebStorm, I navigate to the localhost:8080/myproject/src URL to run it. Within the src folder, there is a js directory structured like this: libraries models place.model.ts place.model.js addr ...

Challenges arise when working with arrays: Attention required - Offset 0 undefined

I have encountered a challenge with my PHP code. I am attempting to convert an HTML table into an array and then execute a mysqli query, but I am unsure about the process. In my code, I have a variable $aDataTableDetailHTML[][]. The first set of brackets ...

Warning: Using synchronous XMLHttpRequest on the main thread is no longer recommended as it can negatively impact the user's experience

I encountered an issue with my project while attempting an Ajax request [Warning] Using synchronous XMLHttpRequest on the main thread is now considered deprecated due to its negative impact on user experience. function retrieveReviews() { var reviewsD ...

Using blending modes with gradient colors in an SVG design

I'm struggling to get my logo to change colors upon scrolling into a button with similar gradient colors, but I just can't seem to make it work. Can anyone lend me a hand? Thank you! Take a look at my Logo. I've attempted to add some styles ...

What could be the reason why both the add and remove functions are unable to work simultaneously within a JavaScript function?

Hi there! I recently started diving into JavaScript and encountered a little hiccup. I've been working on a dice game where images change randomly whenever a button is clicked. The images transition from one to another, but I wanted to add a rolling ...

Combine two columns into a single table column using HTML/CSS and JavaScript with the help of Datatables

I utilize the DataTables library from https://datatables.net/ to create sortable and searchable tables on my website. However, my table becomes too wide due to the numerous columns it contains. I am looking for a way to condense the width by merging relate ...

Finding the median value within a collection of objects

I am working with an array of objects containing book details: const booksData = [{"author":"john","readingTime":12123}, {"author":"romero","readingTime":908}, ...

Modify the standard localStorage format

I'm encountering a dilemma with my two applications, located at mysite.com/app1 and mysite.com/app2. Both of these apps utilize similar localStorage keys, which are stored directly under the domain "mysite.com" in browsers. This setup results in the l ...

Calling an ajax request to view a JSON pyramid structure

My experience with ajax is limited, so I would appreciate detailed answers. I have a Pyramid application where I need to load information via ajax instead of pre-loading it due to feasibility issues. I want to retrieve the necessary information through a ...

Adding schemas to the router of a Next.js 13 app is a helpful feature that can

Summary: In Next.js 13, the /app router's new changes to layout and page routing have altered how we add content to the <head>. The challenge now is how to include a schema script on each page. Next.js automatically combines <head> tags f ...

"Enhancing event handling: Using addEventListener natively with selectors similar to .on()

Has anyone figured out how to replicate jQuery's .on() method in vanilla JavaScript? The native addEventListener function doesn't seem to have the capability to filter based on child/selector elements, and delving into event bubbling and capturin ...

Determine the total of all the values displayed in the footer of a jQuery

I am looking to show the total amount in the footer of a jquery datatable. Below is a snapshot of my datatable: https://i.stack.imgur.com/z01IL.png Here is the code snippet for my jquery datatable: for (var i = 0; i < length; i++ ) { var patient = ...

The hamburger menu on the responsive navbar fails to open when clicked on

Having an issue with my navbar in mobile and responsive environments. The hamburger menu shows up, but when clicked on, the links are not displayed. Below is the code that I am using, all the necessary links are included but the menu is not functioning pro ...