1

I am trying to use click and keydown together but having a problem by pressing key. Is it possible that if we can join both events in one statement.

HTML

 <audio id="Q" src="https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3"> </audio>
 <div>
      <button name="Q">Q</button>
</div>

JavaScript

    const queButton = document.querySelector("[name=Q]");
    queButton.addEventListener("click", function() {
            document.getElementById("Q").play();
    });    

    queButton.addEventListener("keydown", function(e) {
            if (e.key == 81) {
                document.getElementById("Q").play();
            }
    });

1 Answer 1

2

Because audio playback only occurs when a specific key is pressed, it's not possible to share the entire event handler between both the click and keydown events.

It is however possible to define a reusable function (ie playSoundQ()) that is called for both events as shown below:

/* Define reusable play sound function for both events */
function playSoundQ() {
  document.getElementById("Q").play();
}

const qButton = document.querySelector("[name=Q]");
/* It's possible to pass the playSoundQ directly as the event handler
here, seeing there's no additional logic in the event handler */
qButton.addEventListener("click", playSoundQ);

/* Add keydown event listener to document rather than button */
document.addEventListener("keydown", function(e) {

  /* Change to keyCode */
  if (e.keyCode == 81) {
    playSoundQ();
  }
});
<audio id="Q" src="https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3"></audio>
<div>
  <button name="Q">Q</button>
</div>

Note also that a few fixes have been applied here; the keydown listener is added to the document rather than the button to ensure key based playback is reponsive to all key events that occur in the browser. The e.key in your keydown handler has also been corrected to e.keyCode to ensure that playback happens when the "Q" key is pressed.

Hope that helps!

Sign up to request clarification or add additional context in comments.

1 Comment

@user6642297 please consider accepting the answer if it has been helpful by clicking the grey tick next to the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.