Reputation: 2699
I am trying to make a list navigable using the up/down arrow keys - which worked but pressing these keys causes the window to scroll which is very annoying. So I want to disable to movement of the page using the arrow keys when this box is focused.
I tried:
$('.selectionList').focus(function(event){
$(document).keydown(function(e) {
return false;
});
});
$('.selectionList').blur(function(event){
$(document).keydown(function(e) {
return true;
});
});
But the re-enabling of these keys did not work to the page wouldn't scroll without the scrollbar. I found this which I could use but this would disable the use of these keys permanently, which I do not want to happen.
The $('.selectionList').keyup() event is as follows:
$('.selectionList').keyup(function(event){
if (event.keyCode == 13) //enter
{
$('.listNameBox a').click();
}
else
{
if ((event.keyCode == 38) && ($(this).children('li:eq(' + ($('.selectionList li.selected').index() - 1) + ')').length > 0)) //up
{
selectListItem($(this).children('li:eq(' + ($('.selectionList li.selected').index() - 1) + ')'));
}
else if ((event.keyCode == 40) && ($(this).children('li:eq(' + ($('.selectionList li.selected').index() + 1) + ')').length > 0)) //down
{
selectListItem($(this).children('li:eq(' + ($('.selectionList li.selected').index() + 1) + ')'));
};
}
});
Any help would be appreciated.
Upvotes: 3
Views: 5839
Reputation: 150040
Your .blur()
handler isn't replacing the previous keydown handler, it's adding another one. (And subsequent focus and blur events keep adding more and more.)
Try instead using $(document).off('keydown')
or $(document).unbind('keydown')
in your .blur()
handler to remove the previous keydown handler.
The .off()
method is new in jQuery 1.7 and pairs with .on()
, but for older versions you can use the .unbind()
method. If you have a look at the doco I've linked to you'll see that jQuery gives you control over exactly which handlers are being unbound, but in your case the simple syntax with the event name should be fine.
Upvotes: 0
Reputation: 65785
use jQuery .on()
and .off()
inserted of binding events like that. It would solve your problem.
function prevent(event){
event.preventDefault();
return false;
}
$('.selectionList').on('focus', function(){
$(this).on('keydown', prevent);
});
$('.selectionList').on('blur', function(e){
$(this).off('keydown', prevent);
};
Upvotes: 1