Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop spacebar from scrolling page

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?

like image 658
sir_thursday Avatar asked Jul 16 '12 23:07

sir_thursday


1 Answers

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.

like image 186
nnnnnn Avatar answered Oct 18 '22 02:10

nnnnnn