Connecting Tech Pros Worldwide Forums | Help | Site Map

Associating keys to a function

francescomoi@usa.com
Guest
 
Posts: n/a
#1: Jul 24 '05
Hi.

I wonder if I can associate some keys (e.g. 'Ctrl+T') to some
function I create with JavaScript on my webpage.

Thank you very much.


Jeff North
Guest
 
Posts: n/a
#2: Jul 24 '05

re: Associating keys to a function


On 23 Jul 2005 17:39:25 -0700, in comp.lang.javascript
francescomoi@usa.com wrote:
[color=blue]
>| Hi.
>|
>| I wonder if I can associate some keys (e.g. 'Ctrl+T') to some
>| function I create with JavaScript on my webpage.
>|
>| Thank you very much.[/color]

You could use the ACCESSKEY attribute but these use the ALT+ sequence.

Google on ACCESSKEY or here is a link with associated CSS for
displaying the shortcut key:
http://www.alistapart.com/articles/accesskeys/
---------------------------------------------------------------
jnorthau@yourpantsyahoo.com.au : Remove your pants to reply
---------------------------------------------------------------
Yann-Erwan Perio
Guest
 
Posts: n/a
#3: Jul 24 '05

re: Associating keys to a function


francescomoi@usa.com wrote:

Hi,
[color=blue]
> I wonder if I can associate some keys (e.g. 'Ctrl+T') to some
> function I create with JavaScript on my webpage.[/color]

This is an interesting problem, which unfortunately cannot be solved in
a cross-browsers way. Not only browsers do not manage key events in the
same way (event type, key codes, modifiers), but also browsers already
attach macros to key shortcuts and might prevent addityional code to be
run (of course these shortcuts differ across user agents).

As a result, if you target the web, then don't even try further and
simply reconsider the way you trigger your functions (for instance only
use buttons) - indeed having something work in one browser is likely to
not work elsewhere, and even potentially breaking a core functionality.

If targeting only one browser (e.g. in an intranet), then it might be
interesting to study its key event model and develop specific code - it
depends on how much time you have:-)

Anyway, just for the sake of the exercise, a short example follows, with
a dirty hack for IE.


---
<script type="text/javascript">
// bind method
var bind=(function(){
var macros=[];

document.onkeypress=function(evt){
evt=evt||window.event;

var k=evt.keyCode||evt.which;
var hasCtrl=evt.ctrlKey ? bind.CTRL : 0;

/*@cc_on if(hasCtrl) k+=0x60; @*/

var key=String.fromCharCode(k).toLowerCase();
for(var ii=0, m; ii<macros.length; ii++) {
m=macros[ii];
if(m.key==key && m.modifiers==hasCtrl){
m.func(evt);
}
}
if(window.focus) window.focus();
}

return function(func, key, modifiers) {
macros[macros.length]={
func:func,
key:key.toLowerCase(),
modifiers:modifiers||0
};
}
})();

bind.CTRL=1;


// test
function test1(){alert("test1");}
function test2(){alert("test2");}

bind(test1, "y");
bind(test2, "y", bind.CTRL);
</script>
---


HTH,
Yep.
Closed Thread