AKG
AKG

Reputation: 3286

event.preventDefault behaving weirdly in Firefox on keydown

The code below is effective in preventing the browser default from firing in Chrome and Safari. For some reason, however, my code does not fire even after pressing the arrow key in Firefox.

$(window).keydown(function(e) {
    switch(e.which){
        case 39: //right arrow key
            e.preventDefault();
            $('body').scrollLeft(scrollNow + z(10));
            break;
        case 37: // left arrow key
            e.preventDefault();
            $('body').scrollLeft(scrollNow - z(10));
            break;
    }
});

I tried return false; instead of e.preventDefault(); too, but to no effect. I also tried putting e.preventDefault(); after the scrollLeft line, but it isn't working either. Any ideas?

Upvotes: 1

Views: 648

Answers (4)

Erutan409
Erutan409

Reputation: 752

I just came across this issue, myself. I added an event listener for a select input's keydown event to disable left/right keys from traversing the options top/right, respectively. It works perfectly in Chrome and IE. Based on what I've read, so far, it definitely is a bug that has had a lot of debate and speculation on whether or not to actually treat it as a bug. I even went as far as to attach another event listener to the aforementioned select input for keyup; which I noticed was triggering, too, after invoking preventDefault from within the keydown event (Firefox). However, the action is not prevented. Pretty annoying.

Still trying to determine a workaround.

Upvotes: 1

Rohan Kumar
Rohan Kumar

Reputation: 40639

Try this,

Updated

$(window).keydown(function(e) {
    var code = (e.keyCode ? e.keyCode : e.which);
    switch(code){
        case 39: //right arrow key
            e.preventDefault();
            $('body').scrollLeft(scrollNow + z(10));
            break;
        case 37: // left arrow key
            e.preventDefault();
            $('body').scrollLeft(scrollNow - z(10));
            break;
    }
});

Upvotes: 0

isJustMe
isJustMe

Reputation: 5470

Try this:

$(window).keydown(function(e) {
    switch(e.keyCode){
        case 39: //right arrow key
            e.preventDefault();
            $('body').scrollLeft(scrollNow + z(10));
            break;
        case 37: // left arrow key
            e.preventDefault();
            $('body').scrollLeft(scrollNow - z(10));
            break;
    }
});

Upvotes: 2

Adil Shaikh
Adil Shaikh

Reputation: 44740

try this -

code = e.keyCode || e.which;
switch(code){

Upvotes: 2

Related Questions