javascript prevent cursor to move
Asked Answered
I

1

5

Into an input box, I want to stop the propagation of the cursor just as I type on the up key "↑" :

Before :

tes|t // cursor is before t

After :

|test // cursor went beginning

I want to prevent the cursor to move, so it has to stay before t.

So far, I'm trying with this, but it doesn't work :

$('input').keyup(function(e) {

    if (e.which == 40) { // up key
        e.stopPropagation();
        e.stopImmediatePropagation();
        e.preventDefault();

        // actions

        return false;
    }

}

Is this possible anyway ?

Induct answered 29/3, 2013 at 22:35 Comment(3)
Try keydown instead of keyup.Saintly
That's probably not a good idea. I personally rely on this behaviour when typing (albeit rarely)...Butterfield
@FabrícioMatté: That works just great with keydown :)Induct
F
8

You can use keydown for that:

$('input').keydown(function(e) {
    if (e.which == 40) { // up key
        return false;
    }
}

keyup fires after the keypress event has been handled and keypress is supposed to not fire for non-printable characters (though there are some inconsistencies across different browsers), so preventing the event's default action right at keydown is the best course of action.

Keep in mind that if you don't have a good reason for preventing the default action (e.g. going through an autocomplete list while having the search field focused), you may be affecting other users' usability as commented by @Kolink.

Falster answered 29/3, 2013 at 22:43 Comment(5)
Just to be exact, keypress doesn't fire for non-printable characters in any browser, though there are some differences, which characters are counted as printable, between browsers.Fiora
@Fiora I'm aware that keypress is supposed to not fire for non-printable characters, but in fact it does for Chrome.Saintly
@Fiora Strange, just tested in latest stable Chrome and it no longer fires the keypress event for arrow keys. Well, updated the answer to clean up that. =]Saintly
There really are some inconsistencies across different browsers, for example FF19 and IE10 fires onkeypress for ESC (how to print it?), but Chrome25 doesn't... +1 anyway : ).Fiora
Many years later but this isn't working for me (Chrome on OS X)Helpless

© 2022 - 2024 — McMap. All rights reserved.