user3767064
user3767064

Reputation: 11

Adding a shortcut key to an html element using JS

<li><a href="javascript:onUsersClick();" id="masterUsersMenu">Users</a>

How can I add a shortcut key combination to the above html element. Something like

<li><a href="javascript:onUsersClick();" id="masterUsersMenu" shortcut= "Ctrl+U">Users</a>   

so that when "Ctrl+U" is pressed the method is called automatically.

Upvotes: 0

Views: 3716

Answers (4)

小弟调调
小弟调调

Reputation: 1333

A robust Javascript library for capturing keyboard input and key combinations entered. It has no dependencies.

https://jaywcjlove.github.io/hotkeys-js/

hotkeys('ctrl+a,ctrl+b,r,f', function(event,handler){
    switch(handler.key){
        case "ctrl+a":alert('you pressed ctrl+a!');break;
        case "ctrl+b":alert('you pressed ctrl+b!');break;
        case "r":alert('you pressed r!');break;
        case "f":alert('you pressed f!');break;
    }
});

Upvotes: 0

Just code
Just code

Reputation: 13801

You may need to read msdn

Use jQuery. You may need to refer a demo here: http://jsfiddle.net/lesson8/sjNLs/

After all, if you need to use access key in a anchor you can see demo here:

http://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_global_accesskey

Remember accesskey works with alt.

Upvotes: 1

Linga
Linga

Reputation: 10563

Try using this JQuery

$(document).keypress("U",function(e) {
    if(e.ctrlKey){
        onUsersClick();
    }
    return false
});

Upvotes: 0

Yaje
Yaje

Reputation: 2831

use accesskey

for example :

<li><a href="javascript:onUsersClick();" id="masterUsersMenu" accesskey="PREFFERED_ACCESS_KEY">Users</a> 

the way to trigger the access key depends on the browser you are using and the accesskey value you put in the element

for detailed info to use access keys refer Here

Upvotes: 3

Related Questions