lhan
lhan

Reputation: 4635

Prevent page-scrolling with arrow keys, but still allow cursor to move within text field?

Is it possible, using JavaScript, to prevent arrow keys from scrolling a page (horizontally, in this example), yet still allowing the arrow keys to move the cursor within a text field?

For example - I have a text input in a super-wide <div>, and when I use arrow keys to move the cursor to the end of the text, it will then scroll the page horizontally.

I know that I can use event.preventDefault(); to prevent the default behavior, but this also prevents the cursor from moving. I've also tried e.stopPropagation();, which doesn't seem to do the trick either.

Is it possible to do this, or will I have to use e.preventDefault(); and then manually move the cursor position with JavaScript as well? I'm hoping for a simpler solution that that. :)

Here's a JSFiddle demonstrating my issue: http://jsfiddle.net/h6ug57u0/

EDIT:

I should note that I'm only trying to achieve this behavior when there is focus in an input. Otherwise, I don't want to hamper with the browser's default behavior - I know many users use the arrow keys to scroll.

Upvotes: 3

Views: 1314

Answers (2)

Lai32290
Lai32290

Reputation: 8548

Maybe you need check position of input caret for analyse if you e.preventDefault() or not.

Fallow a example:

http://jsbin.com/cunidinuvo/edit?html,js,output

Upvotes: 2

David P
David P

Reputation: 2093

Why don't you just add an onkeypress event handler to the textbox, and then check for arrow keys?

Upvotes: 0

Related Questions