Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript prevent cursor to move

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 ?

like image 577
Menencia Avatar asked Mar 29 '13 22:03

Menencia


1 Answers

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.

like image 177
Fabrício Matté Avatar answered Sep 22 '22 17:09

Fabrício Matté