cuppajoeman
cuppajoeman

Reputation: 337

How to a mouseclick event by pressing a keyboard button in Javascript

How can I trigger a mouseclick event on a certain element on a web page by pressing a button on my keyboard using vanilla javascript?

Upvotes: 0

Views: 55

Answers (3)

cuppajoeman
cuppajoeman

Reputation: 337

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'

Upvotes: 1

Ilan P
Ilan P

Reputation: 1792

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>

Upvotes: 2

Griehle
Griehle

Reputation: 114

simulate(document.getElementById("btn"), "click");

Upvotes: 0

Related Questions