views:

41

answers:

1

Hello, I've made a slider that uses the left and right arrow keys to move the slide but when pressed to quickly it will bug a little and I was wondering if it's possible to limit the amount of presses in say a second. You can see it here: [link removed]

$('#slider-nav div').click(function() {
    $('#slider-nav div').removeClass('selected').addClass('');
    $('#slider-nav div:eq('+($.jcarousel.intval($(this).text())-1)+')').addClass('selected');
})

// Allow left and right keys to control slider
$(document.documentElement).keypress(function(e) {
    var code = (e.keyCode ? e.keyCode : e.which);
    var direction = null;

    // handle cursor keys
    if (code == 37) { // left key
        direction = 'prev';
    }
    else if (code == 39) { // right key
        direction = 'next';
    }

    if (direction != null) {
        $('#slider-nav div.selected')[direction]().click();
    }
});
+1  A: 

You can add a global variable and then when the key is pressed set it to getTime() and then on the next call, check if the difference in the set time and the current time is less than 1000.

    var checkTime = 0;
function onKeyPress(){
    var currentTime = new Date()
    if((currentTime.getTime() - checkTime) > 1000){
        //do stuff;

        checkTime =currentTime.getTime();
    }
}
Aaron Harun
This worked, thank you very much! I'll still accept better solutions though, if there are anyway. :)
Jaybuz