Reputation: 21
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?
Upvotes: 0
Views: 1985
Reputation: 2930
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();
}
});
Upvotes: 2
Reputation: 46
Instead of binding the event listener to that input element, bind the listener globally like this document.addEventListener("keyup", your_function_here);
Upvotes: 0
Reputation: 2206
you can bind the keyup event on window or document
window.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
console.log("oops!")
}
});
Upvotes: 1
Reputation: 5322
You can use document
When use input.addEventListener
then it will listen event from input only and when use document.addEventListener
then it will listen from the entire page
var input = document.getElementById("myInput");
document.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("myBtn").click();
}
});
<form>
<input id="myInput" placeholder="Some text.." value="">
<input type="submit" id="myBtn" value="Submit">
</form>
Upvotes: 1