jQuery keyboard navigation : dysfunction with mouse

jQuery keyboard navigation : dysfunction with mouse

Hi


I have a script for a keyboard navigation that partially works.


When I'm on the home page (top of page) and I press the "down" key on my keyboard the page scroll fine to the next section. The problem is that if I scroll with my mouse in the middle of the page, or at the bottom of the page and I want to use the keyboard to get to the next section (on top or bottom) it doesn't work. In fact I have a counter system that lets you navigate between sections $ ('.layout') but this system shows its limits.


So I'm confused and I need some help please. What can I add in my code for that my keyboard navigation works fine anywhere in the page ?

http://jsfiddle.net/Xroad/LPvS9/7/




$(function () {
    var positions = []
    $('.layout').each(function () {
        positions.push(parseInt($(this).offset().top));
    })

    var count = 0
    var x = positions.length - 1
    $(window).keydown(function (event) {
        switch (event.keyCode) {
            case 38:
                if (count >= x * (-1) && count !== 0) {
                    count--
                    $('#page').stop().animate({
                        scrollTop: positions[count]
                    }, 700);
                } else {
                    event.preventDefault()
                }

                break;

            case 40:
                if (count <= x) {
                    count++
                    $('#page').stop().animate({
                        scrollTop: positions[count]
                    }, 700);
                } else {
                    event.preventDefault()
                }

                break;
        }
    });
});