Search code examples
jqueryhorizontal-scrollingkeydownpreventdefault

How to enable events after using jquery.preventdefault?


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?


Solution

  • You just need to unbind existing handler

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