depiction
depiction

Reputation: 819

preventDefault doesn't work on pageup or pagedown in Chrome or Safari

I'm working on adding keyboard controls to a datepicker for accessibility. I want to use pageup and pagedown keys to toggle between the next and previous months. As part of the code I'm using e.preventDefault to prevent the page from being scrolled up or down only when the datepicker is open. I have it working in Firefox and IE, but not in Chrome or Safari.

I'm not posting the full code here, but I created test code below. No matter what I try, the page still scrolls up/down when these keys are pressed in Chrome or Safari. I can't use up, down, left, or right keys because they are used to navigate the focus between days within each month.

$(window).keyup(function(e) {
    console.log(e.keyCode);
    if(e.keyCode === 34) {

        console.log('page down');

        e.preventDefault();
        e.stopPropagation;
        e.stopImmediatePropagation();
        return false;
}

Upvotes: 1

Views: 1027

Answers (1)

Blake Plumb
Blake Plumb

Reputation: 7209

There are a couple issues with the code.

You can't prevent a default action of a key on keyup. By that time the code has already run. It has to be on keydown.

The second problem is that the keyCode is an integer not a string so your if statement is not going to be entered into.

http://jsfiddle.net/ymr744p4/

$(window).keydown(function(e) {
    console.log(e.keyCode);
    if(e.keyCode === 34) {
        console.log('page down');
        e.preventDefault();
    }
});

Upvotes: 3

Related Questions