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!
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!
Share Improve this question edited Jan 30, 2013 at 19:50 Ben Kirchner asked Jan 30, 2013 at 19:01 Ben KirchnerBen Kirchner 3033 silver badges9 bronze badges 4- 1 tried return false instead of e.returnValue=false;? – Suresh Atta Commented Jan 30, 2013 at 19:02
-
like @TheSureshAtta at the bottom of your function put
return false;
instead of youre.returnValue = false;
– Ryan Commented Jan 30, 2013 at 19:10 - you need both e.preventDefault(); and e.stopPropagation(); – geniuscarrier Commented Jan 30, 2013 at 19:37
- I tried return false, and e.stopPropagation(); still scrolling! I've looked all over the web. I'm out of ideas! – Ben Kirchner Commented Jan 30, 2013 at 19:47
1 Answer
Reset to default 12You 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.