I have a live search input that shows results and lets you use the up and down arrows when the results popup but I want to prevent the cursor from moving left or right when using the up and down arrows. I cannot figure this out. I tried e.preventDefault()
with no luck. Here is what I have tried:
if(e.which == 40){
e.preventDefault();
current = results.find('li.hover');
current.removeClass();
var next = current.next('li');
if(next.length == 0){
next = current.parent().parent().parent().next().find('li:first');
/* Go back to the top */
if(next.length == 0){
next = results.find('li:first');
}
}
next.addClass('hover');
return false;
}
Thanks!
I have a live search input that shows results and lets you use the up and down arrows when the results popup but I want to prevent the cursor from moving left or right when using the up and down arrows. I cannot figure this out. I tried e.preventDefault()
with no luck. Here is what I have tried:
if(e.which == 40){
e.preventDefault();
current = results.find('li.hover');
current.removeClass();
var next = current.next('li');
if(next.length == 0){
next = current.parent().parent().parent().next().find('li:first');
/* Go back to the top */
if(next.length == 0){
next = results.find('li:first');
}
}
next.addClass('hover');
return false;
}
Thanks!
Share Improve this question asked Nov 12, 2011 at 23:00 mikelbringmikelbring 1,4922 gold badges14 silver badges24 bronze badges 1-
1
As an aside, try using
.closest()
(ref) instead of multiple.parent()
functions - just to keep things more readable ;) – Mottie Commented Nov 12, 2011 at 23:15
2 Answers
Reset to default 17Are you binding this onkeyup or keydown? If you are using keydown, you can prevent it, if your using keyup, the event already happened. Otherwise e.preventDefault() should be working.
You could do something like...
$('#content').on('keydown', function(event) {
var key = event.originalEvent.key;
if (key == 'ArrowDown' || key == 'ArrowUp') {
event.preventDefault();
}
});
$('#content').on('keyup', function(event) {
// do stuff
});