user6642297
user6642297

Reputation: 393

how we can add two event listeners click and keydown in javascript

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

Upvotes: 1

Views: 4822

Answers (1)

Dacre Denny
Dacre Denny

Reputation: 30360

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!

Upvotes: 2

Related Questions