Lukas
Lukas

Reputation: 7734

Body stop scrolling after keydown, keypress with jQuery

I have some scrolling actions after keydown, keypress pressing. So this is what it looks like:

$(document).keydown(function(e) {
    e.stopPropagation();

    if (e.keyCode === 40) {
        // some scrolling actions in specifie div
    } else if (e.keyCode === 38) {
        // some scrolling actions in specifie div
    }
});

Everithing is working fine but when im scrolling, keypressing with my div scrolls also whole page. Is there any option to stop this body scrolling?

Upvotes: 3

Views: 3495

Answers (2)

Reinstate Monica Cellio
Reinstate Monica Cellio

Reputation: 26143

You need .preventDefault() in there...

$(document).keydown(function(e) {
    e.stopPropagation();
    if (e.keyCode === 40) {
        e.preventDefault();
        console.log(40);
    } else if (e.keyCode === 38) {
        e.preventDefault();
        console.log(38);
    }
});

Upvotes: 5

Adam Merrifield
Adam Merrifield

Reputation: 10407

If your body is what currently has the scrolling animation then use stop(). http://api.jquery.com/stop/

$('body').stop();

Upvotes: -2

Related Questions