Search code examples
jqueryarraysonkeydownonkeyup

jQuery - Up and Down keys to get values from array


I have an array of sections. using the up and down arrow keys, I would like to get the current and the next value and do not loop as shown below.

var sections = [ "A", "B","C","D"];

$(document).keydown(function(e){

    var k= e.which;

    if(k==40){ sections.push( sections.shift() ); }

    else if(k==38){ sections.unshift( sections.pop() ); }

    $('body').html( 'You just went to ' + sections[0] ); // current section.
    // How to return the previous section that I was in?
    // For example: You just left section A then went to section B
    // Do not loop, return: You just reached end/beginning
});

Working fiddle: http://jsfiddle.net/9977ov2x/


Solution

  • try it

    var sections = ["A", "B", "C", "D"];
    var i = 0;
    var $pre = $('p');
    var $now = $('span');
    var $next = $('div');
    $(document).keydown(function (e) {
    
        var k = e.which;
        var pretmp = sections[i] ;
        //Next is same to it you put the variables to the if block below and then echo 2 line in some html tag " if press up will be " and " else will be " so you will have 2 next tmp var i assume it next1 and next2
        if (k == 40) {
            i++;   
            // next1
        } else if (k == 38) {
    
            i--;
            //next2
        }
    
        if (i >= sections.length) {
            i = 0;
        } else if (i < 0) {
            i = sections.length - 1;
        }
        $pre.html('Previous is ' + pretmp);
        $now.html('You just went to ' + sections[i]); // return the current section.
        // How to return the previous section?
        // For example: You just left section A then went to section B
        // Also stop if I'm at the end or begaing then return: You just rech end/beginig
    });
    

    and html in the body

    <p></p><span></span><br/><div></div>