8

I know that e.preventDefault(); is supposed to stop the spacebar from scrolling on the page, but it is not working on my function

$("html").live("keyup", function (e) {
    var code = (e.keyCode ? e.keyCode : e.which);
    if ((code == 32 || code == 13) && $("span").is(":focus")) {
        openDropdown();
        $(".dropdown a.PivotItem:first").focus();
        e.preventDefault();
    } else if ((code == 32 || code == 13) && $("a.PivotItem").is(":focus")) {
        closeDropdown();
        changeSelected($("*:focus"));
        e.preventDefault();
    } else if (code == 27 && ($("span").is(":focus") || $(".dropdown a.PivotItem").is(":focus"))) {
        closeDropdown();
        $("span").focus();
    } else {
        //do nothing
    }
});

Does it have something to do with the .live( handler I have included?

sir_thursday
  • 5,270
  • 12
  • 64
  • 118
  • 1
    Do your other keys do what's expected? In a very quick test in Chrome, the scroll happens on key down, rather than key up, so you may be trying to capture the key press too late – MrOBrian Jul 16 '12 at 23:40
  • @Purmou I'm not changing default behaviors in this function, I am adding accessibility to traversing the navigation with the keyboard. – sir_thursday Jul 16 '12 at 23:44

1 Answers1

22

The space-bar scrolls the page on keydown, not on keyup, so try:

$("html").on("keydown", function (e) {
   // etc

You don't really need to use .live(), because the html element will exist when your code runs.

Also, jQuery normalises event.which so you don't need to test for event.keyCode.

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
  • 2
    So my code doesn't work because I am preventing the default event of the space bar on keyup, which happens to be nothing. Weird, thanks! – sir_thursday Jul 16 '12 at 23:44