fr**********@usa.com wrote:
Hi,
I wonder if I can associate some keys (e.g. 'Ctrl+T') to some
function I create with JavaScript on my webpage.
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.