Reputation: 535
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>
Upvotes: 1
Views: 1639
Reputation: 538
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.
Upvotes: 0
Reputation: 2042
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?
Upvotes: 0