javascriptkeyboard-shortcutsmousetrap

Making Mousetrap click a link


If I have a link and want to bind a keyboard shortcut to, how should I do that? This doesn't seem to work:

<a id="next" href="/next/page">Next page</a>
<script src="mousetrap.js"></script>
<script>
  Mousetrap.bind("n", function() {
    document.getElementById("next").click();
  });
</script>

Solution

  • There are couple of reasons why I believe your code is not working and as I am not a JS expert; I am only saying this from my little experience.

    I have tried to my thinking into a little solution; please have a look below and see if you can work out where you might be going wrong. I will let some one more experienced with JS tell you what is exactly wrong and why it is not working.

    <html>
    <head>
    <title>mouse trap test</title>
    </head>
    <body>
        <a id="next" href="next/page">Next page</a>
    <script src="mousetrap.js"></script>
    <script>
    
    function GoToLocation(url)
      {
        //window.location = "http://www.stackoverflow.com";
        window.location = url;
      }
    
      Mousetrap.bind("n", function() {
        //alert('N pressed' + document.getElementById("next").href);
        //document.getElementById("next").click();
        GoToLocation(document.getElementById("next").href);
      });
    
    
    </script>
    </body>
    </html>
    

    I hope the above helps.