How can I trigger a mouseclick on a certain element on a page by pressing a other button on my keyboard ex "enter" or combination of other buttons?
Asked
Active
Viewed 35 times
0
-
Take a look here: https://stackoverflow.com/questions/6157929/how-to-simulate-a-mouse-click-using-javascript – Adam H Jul 18 '18 at 20:25
-
What have you tried so far? – Adrian J. Moreno Jul 18 '18 at 20:25
3 Answers
2
Try this code out:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">
<title>Ilan's Test</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-12" id="results">
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js" integrity="sha384-o+RDsa0aLu++PJvFqy8fFScvbHFLtbvScb8AjopnFD+iEQ7wo/CG0xlczd+2O/em" crossorigin="anonymous"></script>
<script>
// We begin listening to keypresses on the document body
$(document).keypress(function(e) {
// If the key pressed was Enter (keycode 13)
if (e.keyCode == 13) {
// Perform an action -- You can now envoke a click event on an element's ID for example, here I just console log and append text to my results div
$('#results').append('<div>You hit enter!</div><hr>');
// Console log
console.log('you pressed enter');
return false;
}
});
</script>
</body>
</html>

Ilan P
- 1,602
- 1
- 8
- 13
1
I figured it out with vanilla JS
window.onkeyup = function(e) {
var key = e.keyCode
if (key == 13) {
document.getElementById('test').click()
}
}
This will watch for when someone presses a button then check if they pressed enter, if they did then it will preform a click on the the element with Id 'test'

cuppajoeman
- 252
- 5
- 13
0
simulate(document.getElementById("btn"), "click");

Griehle
- 114
- 1
- 10
-
simulate is not a vanilla JS function, what library is this from and how does it help answer the question? – Luca Kiebel Jul 18 '18 at 21:10
-