Question

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>
Was it helpful?

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.

  • you are assuming that there is onClick function defined for Anchor tag. Even if it is - you have not defined what happens in that onclick function.

  • you should use an external function to achieve the same; so effectively have an anchor tag that use can click and a function which also takes the user to the desired page when the user presses 'N'.

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.

OTHER TIPS

Is there a specific reason you need to click the link? Would something like this work for you instead?

Mousetrap.bind("n", function() {
    window.location.href = "/next/page"; //Or document.getElementById('next').href as in Robert's response.
});

Also, this may help: How do I programmatically click on an element in JavaScript?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top