Unable to utilize the .keyCode method within a query selector

Trying to utilize .keyCode in JavaScript to identify a pressed key, but the console consistently displays null after each key press.

Below is the relevant CSS code:

<audio data-key="65" src="sounds\crash.mp3"></audio>
  <audio data-key="83" src="sounds\kick-bass.mp3"></audio>
  <audio data-key="68" src="sounds\snare.mp3"></audio>
  <audio data-key="70" src="sounds\tom-1.mp3"></audio>
  <audio data-key="71" src="sounds\tom-2.mp3"></audio>
  <audio data-key="72" src="sounds\tom-3.mp3"></audio>
  <audio data-key="74" src="sounds\sound-effect-thriller-1-108404.mp3"></audio>
  <audio data-key="75" src="sounds\tom-4.mp3"></audio>
  <audio data-key="76" src="sounds\flautatravessera-46420.mp3"></audio>

Here is the attempt at JavaScript code:

window.addEventListener('keydown', function(e){
    const audio=this.document.querySelector('audio[data-key="${e.keyCode}"]')
    console.log(audio);
    audio.play();
   }
   )

The issue arises when console.log(audio) returns null.

Answer №1

Employ backticks for denoting template literals.

const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`);

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

Issue arising from CSS and div elements

I am facing some challenges in making certain divs behave as desired. Take a look at the following references: Link 1: - contains two divs Link 2: - has only one div I am trying to utilize two divs (.content) without them being positioned incorrectly ...

The Material-ui paper component fails to display on the screen

The material-ui paper component is implemented on my homepage and functioning correctly. However, when navigating to another page and returning to the homepage, the paper component disappears, leaving only text rendered. Can you help me identify the issue? ...

Strange response received from $http GET request on Android device running Crosswalk

I am attempting to retrieve data in JSON format from an API using AngularJS. The process is successful on iOS and desktop browsers, but I'm encountering a strange response when trying it on my Android device. The request code looks like this: $http({ ...

The request was blocked due to cross-origin restrictions as the CORS header 'Access-Control-Allow-Origin' was found to be missing

I encountered an error while working with AngularJS. The error message reads: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at ... (Reason: CORS header 'Access-Control-Allow-Origin' missing). Below i ...

Locate the nearest index within the array

I'm currently working with an array of "events" where the key assigned to each event corresponds to the Unix Timestamp of that particular event. To illustrate, consider the following array of event objects in JS: var MyEventsArray=[]; MyEventsArray[1 ...

Comparison of Chrome's compatibility with Bootstrap and Edge

Firefox Safari I am facing an issue that seems obvious, but I am unable to pinpoint the exact cause. It just doesn't seem right for no apparent reason. is the website in question. I have tried various troubleshooting methods such as inspecting th ...

What is the method to retrieve JSON data from a URL and showcase the content on a JavaScript page?

I am currently developing a custom MS Teams application and I am facing an issue with fetching JSON data from a URL to display its contents later. Unfortunately, the fetch operation is failing. My objective is to retrieve a list of data from a specified UR ...

Angular Bootstrap Modal provides a sleek overlay for user input forms

Trying to access an angular form within scope for validation purposes. Initial Scenario Consider the following HTML: <body ng-controller='MyAwesomeController'> <form name="fooForm"> <textarea ng-model="reason" required= ...

Utilizing a foundational element to automatically unsubscribe from multiple observable subscriptions

Within our Angular application, we have implemented a unique concept using a Base Component to manage observable subscriptions throughout the entire app. When a component subscribes to an observable, it must extend the Base Component. This approach ensures ...

What are the best practices for incorporating keywords into HTML code for SEO purposes?

Even though this topic is borderline related to programming questions, I believe it's still relevant here. After all, only those of us who are actually coding for a website would be considering this aspect. Lately, I've been delving deeper into ...

Choosing individual child elements, with matching names, from two distinct parent elements with identical names

As a beginner in coding, I understand that my code may be messy and redundant, so I apologize for any confusion it may cause. I am working on adding the final piece to my navigation bar. Below is the HTML code, and a fiddle link will be provided at the en ...

Vue: Conditionally importing SCSS when a component is instantiated

My goal is to import Material SCSS exclusively for my Admin component. While this setup works smoothly during local development, the issue arises when I deploy my site to Firebase hosting - the Material styles start affecting not just my Admin component, ...

Dealing with JWT management in the absence of Cookies

After doing some research on JSON Web Token (which is a new concept to me), I have learned about its secure mechanism for transmitting information between parties without the need for server Sessions. Currently, I am in the process of building a web app f ...

What sets apart Vue-Test-Utils' "mount" from "shallowMount"?

Just to clarify, my experience with Vue, JavaScript, and web frameworks is still pretty fresh. Currently, I am working on getting more familiar with basic unit and component testing using Jest and vue-test-utils. I have gone through the documentation for ...

Use javascript/ajax to create a dynamic dropdown menu

I have successfully retrieved data from an ajax and JSON request on another php page. Using json parse, I was able to extract two array strings. JAVASCRIPT: if (xmlhttp.readyState==4 && xmlhttp.status==20 { var data = JSON.parse(xmlhttp.respon ...

Encountering a JavaScript runtime error while trying to access and interpret JSON

Currently, I'm facing a challenge with converting a C# list of string types into a JSON object. The issue arises when trying to read this JSON object later in JavaScript. On the other hand, the process seems to work fine when dealing with a C# list of ...

Arrange objects in dropdown menu to line up

I'm currently working on a dropdown menu and I have a specific requirement – the menu should always be split into two columns and be able to span multiple lines. However, I've encountered an issue where the columns are not aligned properly, cau ...

Automatically submitting a Google Form using the Google Forms API in conjunction with Google Apps Scripts

Is it possible to integrate a third-party app with Google Forms API and Google Apps Script in order to create timed quizzes that automatically submit once the time limit has been reached? ...

What steps do I need to take to incorporate dialog-polyfill into my React application?

Incorporating Firebase and FirebaseUI in my React application for phone number registration has been successful on Google Chrome desktop. However, when testing it on different browsers, such as through , I encountered an issue with the country code selecto ...

Comparing two tables in jQuery/Javascript for matching data

I want to check for matches between the rows of two HTML tables, where the data in the first cell can be duplicated but the data in the second cell is always unique. The goal is to determine if the combination of values in the first and second cells of tab ...