简体   繁体   中英

Click Button on Enter Key

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM