user2700923
user2700923

Reputation:

Why doesn't preventDefault() stop focus change after a Tab-keypress?

I was fiddling with preventDefault() and must be doing something wrong.

$("#input").bind("keypress", function(event) {
    if(event.which == 9) {
    event.preventDefault();
    alert("You pressed tab.");
    }
});

The tab functionality isn't prevented. What's wrong with this?

Upvotes: 5

Views: 8393

Answers (3)

user2864740
user2864740

Reputation: 61885

The keypress event is simply not fired when the Tab is pressed - this also explains why there is no alert, independent of what preventing the default may do.

Changing the code to use keydown allows the Tab to be caught and prevents the default focus-change (in Chrome1, anyway).

$("#input").bind("keydown", function(event) {
    if(event.which == 9) {
        event.preventDefault();
    }
});

1 I tested the above in Chrome 35 with jQuery 1.6-2.1; it does not work under the KO 3.0 library.

Upvotes: 1

Ernesto
Ernesto

Reputation: 1592

From the documentation on JQuery,

Note: as the keypress event isn't covered by any official specification, the actual behavior encountered when using it may differ across browsers, browser versions, and platforms.

This method is a shortcut for .on( "keypress", handler ) in the first two variations, and .trigger( "keypress" ) in the third.

The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except that modifier and non-printing keys such as Shift, Esc, and delete trigger keydown events but not keypress events. Other differences between the two events may arise depending on platform and browser.

So in this case you are using the wrong event. Also it might have browser compatibility issues.

Upvotes: 1

joshboley
joshboley

Reputation: 1153

Try this FIDDLE. The input loses focus when you tab. Binding to the body fixes this.

$("body").on("keydown", function(event) {
if(event.which == 9) {
event.preventDefault();
    alert("You pressed tab.");
}
});

Upvotes: 2

Related Questions