Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop window scroll with keycode (arrows), event.preventDefault() not working?

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!

like image 223
Ben Kirchner Avatar asked Jan 30 '13 19:01

Ben Kirchner


People also ask

What is the opposite of event preventDefault ()?

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.


1 Answers

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.

like image 104
Plynx Avatar answered Sep 27 '22 16:09

Plynx