Question

How can I enable events after using jquery.preventdefault?

I have this code to prevent the document from scrolling to left and right on the keycode below,

$('body').keydown(function(e){
    if (e.keyCode === 39 || e.keyCode === 37) {
        e.preventDefault();
       // return false;
    }
});

Then I have a button to enable the keycodes above and let the page to be scrolled again,

     $('#pbCloseBtn').click(function(){
        $('body').keydown(function(e){
            if (e.keyCode === 39 || e.keyCode === 37) {
               e.bind('scroll');
               return true;
            }
        });
    });

But it won't work after preventing the page from scrolling.

Any ideas?

Was it helpful?

Solution

You just need to unbind existing handler

$('#pbCloseBtn').click(function(){
    $('body').unbind('keydown'); // <-- removes previous handler
});

OTHER TIPS

You can use on and off :

var preventScroll = function(e){
    if (e.keyCode === 39 || e.keyCode === 37) {
        e.preventDefault();
       // return false;
    }
};
$('body').on('keydown', preventScroll);
$('#pbCloseBtn').click(function(){
    $('body').off('keydown', preventScroll);
});

Demonstration

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top