Xroad
Xroad

Reputation: 425

Keyboard navigation in jQuery : two presses instead of one

I have a keyboard navigation on my page who permit to navigate between the ".layout" classes. The problem is that after the first start of the page it's necessary to press twice the "down" arrow key to trigger the movement of the page. What's wrong ?

Press : "up" and "down" on your keyboard to see : http://jsfiddle.net/Xroad/LPvS9/4/

PS: I have to keep "#page" instead of "html,body" otherwise the code comes into conflict with other functions.

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

            break;

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

            break;
        }
     });
});

Upvotes: 0

Views: 38

Answers (1)

Luk&#225;š Rutar
Luk&#225;š Rutar

Reputation: 316

you initialize

var count=-1

rather do

var count=0

Upvotes: 1

Related Questions