Reputation: 1
I have a script that cycles through a list of sounds,all works well when clicking the button but how can I get the button to trigger on "Enter" please? My working code below:
<div>
<button class="btn-aqua-fxd" id="cycle_button"></button>
</div>
const sounds = ['Power Up', 'Idle', 'Fire!', 'Over Heat!', 'Power Down', 'Party Time!', 'RESET', ];
let sound_index = sounds.length - 1;
const cycle_button = document.getElementById("cycle_button");
//set initial text in button to first sound
cycle_button.innerText = sounds[0];
cycle_button.addEventListener("click", () => {
//get the previous audio and stop it
const last_sound = sounds[sound_index];
const last_audio = document.getElementById(last_sound);
last_audio.pause();
last_audio.currentTime = 0;
//set the sound index to the next one in the sounds list (cycle back if at end)
sound_index = (sound_index + 1) % sounds.length;
const sound = sounds[sound_index];
const audio = document.getElementById(sound);
audio.play();
next_sound = sounds[(sound_index + 1) % sounds.length]
cycle_button.innerText = next_sound;
})
Upvotes: 0
Views: 93
Reputation: 43
Without jquery, you can add a keydown event listener to the body and call cycle_button.click() only if the key pressed is the enter key.
const body = document.querySelector("body")
const cycle_button = document.querySelector("#cycle_button")
body.addEventListener("keydown", (e) => {
if (e.code === "Enter") {
cycle_button.click()
}
})
cycle_button.addEventListener("click", (e) => {
// handle click
})
Upvotes: 1
Reputation: 181
First of all, this isn't a java code, it is javascript.
In javascript, you can use jquery for this problem. For example you can try this code below.
const KEY_ENTER = 13;
$("#divId").keyup(function(event) {
if (event.keyCode === KEY_ENTER) {
$("#buttonId").click();
}
});
Upvotes: 0