0

<li id="add-this" style=""><a href="#">Add this</a></li>

We all know what this does, it activates a script when you press it, but i was wondering if its possible to bind it to a key so when you hit the key it will activate the script. Tried diffent things and searched Google for a few hours now but cant find what im looking for. Im trying to make a script for my site so you can browse it with you keyboard, i can bind a script to a key but got no idea how to do it do this.

Thanks //Nemx

2
  • Just add keypress or keydown handler to the document. PS: may worth trying to use github.com/tzuryby/jquery.hotkeys or to read its code
    – zerkms
    Mar 3, 2013 at 23:24
  • i can add a keydown, but the problem is that i cant get it to click the link, (function(){ document.addEventListener('keydown', function(e) { if( e.which == 68) { >Dont know what to put here to make it work< } }, false); })(); Tried some things, $("add-this").click(); and document.getElementById('add-this').onclick but get the same error in the console when running them: "Uncaught TypeError: Cannot call method 'click' of nul"
    – Nemx
    Mar 4, 2013 at 19:54

1 Answer 1

0

You can add an keydown, keypress or keyup event-handler to the document and trigger a click on your link. Like this (just replace *YOUR_KEYCODE* with the code from the key you want the user has to press):

$(document).keydown(function(e){
    if( e.which === YOUR_KEYCODE ) {
        $("#add-this").click();
    }
});

http://fiddle.jshell.net/QEk33/

6
  • Added that but it only returns with an error: "Uncaught TypeError: Cannot call method 'click' of null", any idea why?
    – Nemx
    Mar 4, 2013 at 0:56
  • @Nemx are you shure that you've replaced YOUR_KEYCODE with a keycode? Here you can get the keycode you need jsbin.com/uyorip/2/quiet
    – yckart
    Mar 4, 2013 at 1:36
  • Well yeah ofcourse I have replaced it, 68 = D. Thats not the problem, its when i press the key i get the error.
    – Nemx
    Mar 4, 2013 at 18:00
  • @nemx which browser do you use?
    – yckart
    Mar 4, 2013 at 21:03
  • Yeah it works just fine, just tried it on another site. Trying to figure out why it doesnt work, anyways ty for your help =)
    – Nemx
    Mar 6, 2013 at 18:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.