I built an autosuggest, and keycode works to navigate up and down through the list, but it scrolls the window. I have tried event.preventDefault() but it is not stopping it. Any ideas? This is what I have tried:
$(document).keyup(function(e) {
e.returnValue=false;
e.preventDefault();
switch(e.keyCode) {
case 40:
suggestionLine++;
$('#suggestionLine_'+suggestionLine).focus();
break;
// etc...
Thank you!
There is no opposite method of event. preventDefault() to understand why you first have to look into what event. preventDefault() does when you call it. Underneath the hood, the functionality for preventDefault is essentially calling a return false which halts any further execution.
You need keydown
, not keyup
.
Why? The default operation that you're trying to prevent happens immediately when you press the key (try it now!). This allows for things like autorepeat, which will send multiple keydown
events before sending a single keyup
event. By the time keyup
is fired, the scrolling has already taken place.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With