I need to disable the movement of the cursor during auto-complete selection. I have a contentEditable div as the search bar for friends. when I type any letters an auto-complete suggestions appear underneath the search bar. During a selection of the auto-complete suggestions, I need to use the arrow keys to select. But this will also move the cursor on the search bar and it will also disable any current selection in the search bar. Can I somehow disable the movement of cursor for some specific buttons/keys on the keyboard in javascript?
Note:
- Setting the cursor at the last position is not a solution for me.
- I want to disable left-, right-, up-, down arrow key and also carriage return key
You can call
preventDefault()on keydown events that have a keycode corresponding to an arrow key or the return key. This will prevent the cursor from moving.The event.keyCode property will be equal to the following during a keydown event:
So, you can attach an event listener to your div and cancel these events if there is an auto-complete suggestion active:
Note: I used addEventListener for simplicity, but for compatibility, you will have to use attachEvent or onkeydown also.
Example jsFiddle.