Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to re-enable default after doing event.preventDefault()

I know this exact question was asked here, but the answer didn't work for what I needed to do so I figured I'd give some example code and explain a bit...

$(document).keypress(
    function (event) {
        // Pressing Up or Right: Advance to next video
        if (event.keyCode == 40 || event.keyCode == 39) {
            event.preventDefault();
            $(".current").next().click();
        }
        // Pressing Down or Left: Back to previous video
        else if (event.keyCode == 38 || event.keyCode == 37) {
            event.preventDefault();
            $(".current").prev().click();
        }
     }
 );

It basically disables the arrow keys to use them for something else, but doing:

$(document).keypress(function () { });

doesn't enable the default function again... I need it to scroll the page without having to create a scroll function for it...

Any ideas?

Thanks,
Matt

like image 725
Matt Avatar asked Apr 09 '10 15:04

Matt


3 Answers

Adding a new handler doesn't replace the previous one, it adds a new one. You may be looking for jQuery#unbind if you're trying to remove the previous handler, but if you're going to be turning this on and off a lot, you probably would be better off with a flag telling you whether to prevent the default or not in your existing handler.

Adding, and later removing, a handler looks like this:

function keypressHandler() { /* ... */};

$('#thingy').keypress(keypressHandler);

// ...elsewhere...
$('#thingy').unbind('keypress', keypressHandler);
like image 103
T.J. Crowder Avatar answered Nov 03 '22 01:11

T.J. Crowder


I'm not sure this is the right way to handle it.

A better way to approach this problem would be to put some kind of check inside your document.keypress instructions.. like..

var enableKeys = false;

$(document).keypress(
    function (event) {
        // Pressing Up or Right: Advance to next video
        if (event.keyCode == 40 || event.keyCode == 39 && enableKeys) {
            event.preventDefault();

            $(".current").next().click();
        }
        // Pressing Down or Left: Back to previous video
        else if (event.keyCode == 38 || event.keyCode == 37 && enableKeys) {
            event.preventDefault();
            $(".current").prev().click();
        }
     }
 );

Then control the enablekeys wherever you feel necessary, either with a hover, or something along those lines.

like image 27
dmp Avatar answered Nov 03 '22 00:11

dmp


function(e){ e.preventDefault(); }

and its opposite

function(e){ return true; }
like image 34
foxybagga Avatar answered Nov 03 '22 00:11

foxybagga