Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent window scroll jquery

I'm developing a select menu replacement in jquery.
First I've to make the new select menu focusable by just adding tabindex="0" to the container.
Then, I disable focus on the original select menu and give focus to the new one. When the new one is focused and you press the up and down arrows the options change accordingly but there's a big problem. As you press the arrows the body moves too.
I tried all these solutions so far with no luck:

$(window).unbind('scroll');
$(document).unbind('scroll');
$('body').unbind('scroll');
$(window).unbind('keydown');
$(document).unbind('keydown');

Check the code here http://pastebin.com/pVNMqyui This code is from the development version of Ideal Forms http://code.google.com/p/idealforms that I'm about to release soon, with keyboard support.

Any ideas why this is not working?

EDIT: Solved!

Found the answer on this post jquery link tag enable disable

var disableScroll = function(e){
    if (e.keyCode === 40 || e.keyCode === 38) {
        e.preventDefault();
        return false;
    }
};
// And then...
events.focus: function(){ $(window).on('keydown', disableScroll); }
events.blur: function(){ $(window).off('keydown', disableScroll); }

It works!

like image 959
elclanrs Avatar asked Apr 02 '26 00:04

elclanrs


1 Answers

In your keydown handler, for up and down keys, return false like this:

'keydown' : function (e) {
    if (e.keyCode === 40) { // Down arrow
        that.events.moveOne('down');
    }
    if (e.keyCode === 38) { // Up arrow
        that.events.moveOne('up');
    }
    return false;
}

Also, make sure this return gets propagated to the browser's native onkeydown depending on how/which framework you're using.

like image 100
techfoobar Avatar answered Apr 03 '26 15:04

techfoobar