Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent default event action not working...?

I'm trying to add keyboard shortcuts on my website to make fast navigation possible using the keyboard. I'm running into a slight problem, however, with my attempted Alt+X shortcut. The event runs just fine and returns false as it should, but the browser's File menu comes up regardless. I've also tried the preventDefault method, but no change.

The cut-down version of the script is:

document.documentElement.onkeydown = function(e) {
    e = e || window.event;
    switch( e.keyCode || e.which) {
        // some cases here - most notably:
        case 116: // F5 key
            if( activeFrame) {
                activeFrame.contentWindow.location.reload();
                // reloads an iframe if one is active
                return false;
            }
            break;
        // more cases...
        case 88: // X key
            if( e.altKey) {
                // do something
                return false;
            }
    }
}

As noted above, overriding the default action of the F5 key works just fine - the browser reloads the page only if no iframe is active. I don't quite see how to prevent the menu from appearing when Alt+X is pressed.

like image 922
Niet the Dark Absol Avatar asked Oct 25 '11 01:10

Niet the Dark Absol


1 Answers

use stopPropagation(e); instead of preventDefault method

function stopPropagation(e)
{
    e = e || event;/* get IE event ( not passed ) */
    e.stopPropagation? e.stopPropagation() : e.cancelBubble = true;
}

Reference link

Another SO question which mentions that preventDefault has issue in IE.

UPDATE

Try using below code as per MSDN Reference

event.returnValue=false;

And some point from Detecting keystrokes

Some general caveats:

  • Generally, Mac is less reliable than Windows, and some keys cannot be detected.
  • Explorer doesn't fire the keypress event for delete, end, enter, escape, function keys, home, insert, pageUp/Down and tab.
  • Onkeypress, Safari gives weird keyCode values in the 63200 range for delete, end, function keys, home and pageUp.Down. The onkeydown and -up values are normal.
  • Alt, Cmd, Ctrl and Shift cannot be detected on Mac, except in Opera. However, you can always use the altKey, ctrlKey, and shiftKey properties.
like image 60
Harsh Baid Avatar answered Sep 23 '22 08:09

Harsh Baid