Disable move of cursor during auto-complete selection
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 selectio开发者_JS百科n 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:
- 37: Left
- 38: Up
- 39: Right
- 40: Down
- 13: Return
So, you can attach an event listener to your div and cancel these events if there is an auto-complete suggestion active:
var autoCompleteOn = false; //Set this flag in an auto-complete handler
yourDiv.addEventListener("keydown",function(e){
//v------all arrow keys------------v v---Return----v
if(autoCompleteOn && ((e.keyCode >= 37 && e.keyCode <= 40) || e.keyCode == 13)){
e.preventDefault();
return false;
}
}, false);
Note: I used addEventListener for simplicity, but for compatibility, you will have to use attachEvent or onkeydown also.
Example jsFiddle.
Do you use jquery?
if so you should try this
$("#whatever").bind("keypress", function(e) {
if (e.keyCode >36 && e.keyCode <41) return false;
});
Search for javascript keycode for all keys
精彩评论