0

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;
})
1
  • 3
    I don't think this is java code. Did you want to tag javascript? Commented Sep 29, 2022 at 17:16

2 Answers 2

1

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
})
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

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.