views:

256

answers:

2

I'm trying to use jQuery to intercept control-A keypresses on my web page, like so:

$(document).keypress(function (event) {
    if (event.ctrlKey && (event.which == 65 || event.which == 97)) {
        event.preventDefault();
        // ...
    }
});

This works on Firefox, but on IE7, my event handler doesn't get called, and all of the text on the page gets selected instead (as happens on Firefox without the event handler).

Is there any way I can intercept control-A's on IE?

+1  A: 

This works under FF 3.5 and IE7 for me:

 $(function() {
  var isCtrl = false; 

  $(document).keyup(function (e) { 
   if(e.keyCode == 17)
    isCtrl = false;
  }).keydown(function (e) { 
   if(e.keyCode == 17)
    isCtrl = true;

   if(e.keyCode == 65 && isCtrl == true) {
    alert('Intercepted CTRL+A');
    e.preventDefault();
   }
  }); 
 });
Sbm007
Super, thanks! It even works in IE6.
Sean
A: 

If you do a return false in the event handler then it will cancel the browsers behavior. Depending on the browser it can behave differently (for instance keypress will still fire on firefox after a keydown has canceled it, while IE will stop it).

envalid