I want to trigger a button click when the Enter button is pressed in my page. I know how to do it if it's in a form. Like this
<form>
<input id="myInput" placeholder="Some text.." value="">
<input type="submit" id="myBtn" value="Submit">
</form>
<script>
var input = document.getElementById("myInput");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("myBtn").click();
}
});
</script>
But how to trigger the button even when the Enter is pressed irrespective of where the focus is in the input element or not. just pressing the Enter button will trigger the button in the page. How can I do that?
You just need to add your event listener to the document instead of the input
document.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("myBtn").click();
}
});
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments