views:

122

answers:

3

I have some code like this to take over the space bar's function:

 $(document).keypress(function (e) { 
  e.preventDefault();          
  if (e.which == 32) {
   // func
  }
 });

Unfortunately this destroys all key's defaults.

This:

 $(document).keypress(function (e) { 
  if (e.which == 32) {
   e.preventDefault();
   // func
  }
 });

Is unfortunately ineffective.

How can I make it preventDefault of only spacebar?

Thanks.

A: 

Why is it ineffective?

Perhaps you want to use a switch() statement instead of if-then-else ?

Ropstah
+1  A: 

Try this:

//e= e || window.event); you may need this statement to make sure IE doesn't keep the orginal event in motion
var code;  
if (e.keyCode) {
 code = e.keyCode;
} else if (e.which) {
 code = e.which;
 }
if (code == 32) {
 if (e.stopPropagation) {
 e.stopPropagation();
 e.preventDefault();
 }
 return false;
}
TStamper
also see http://www.quirksmode.org/js/events_properties.html#key
Jonathan Fingland
see example in motion:http://www.tedspence.com/index.php?entry=entry070503-103948
TStamper
Also does not work for 192
TStamper
oh of course you're right, it's 96 in FF.
A: 

Try

$(document).keydown(function(e){
if(e.which==32) e.preventDefault();
});

I use it for blocking Esc key and works fine for me.

Thinker
Ah, the mysterious $ function. Reserved for machine generated code by the ECMA spec, but used by half a dozen libraries for different functions in each.
David Dorward
This works for the spacebar, but doesn't work for 192 `, which in Firefox still pops up a search.