Associating keys to a function

F

francescomoi

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.
 
J

Jeff North

On 23 Jul 2005 17:39:25 -0700, in comp.lang.javascript
| 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.

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/
 
Y

Yann-Erwan Perio

(e-mail address removed) 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>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top