I have a button and the following javascript routine.
$("button").keydown( function(key) {
switch(key.keyCode) {
case 32: //space
return false;
}
} );
as I understood it, the return false;
would stop the keypress from being processed. So $("button").click();
would not be called. For other keyCodes, this works as expected. For example, if I intercept40
, which is the down button, the page is not scrolling.
I noticed this behavior in Firefox.
Why does the return false;
does not stop the button click event on space? What does the javascript spec say about this?
Hope this answers your question:
return false;
successfully cancels an event across browsers if called at the end of an event handler attribute in the HTML. This behaviour is not formally specified anywhere as far as I know.If you instead set an event via an event handler property on the DOM element (e.g.
button.onkeydown = function(evt) {...}
) or usingaddEventListener
/attachEvent
(e.g.button.addEventListener("keydown", function(evt) {...}, false)
) then just returningfalse
from that function does not work in every browser and you need to do thereturnValue
andpreventDefault()
stuff from my other answer.preventDefault
is specified in the DOM 2 spec and is implemented by most mainstream modern browsers.returnValue
is IE-specific.First, if you're detecting a printable character such as space, you would be better off with the
keypress
event. Secondly, the way to prevent the default action is to callpreventDefault()
on the event in non-IE browsers and set the event'sreturnValue
property tofalse
in IE.I'm not a jQuery expert and I assume it takes care of obtaining the event for you: