Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choose and select div elements with keyboard arrows and enter keys?

Is there any way of navigating through a grid of div elements by pressing the arrow keys on the keyboard, and "clicking" the selected div by pressing enter key? I know that I should at least try to make this work somehow but I'm completely clueless as for how to make this happen, and if it's even possible.

I'm aware of that the following will be invalid if not using the mouse, so what can I do to show some kind of "focus" on a specific div?

.show:hover{
    width:94px;
    height:94px;
    border:3px solid black;
}

.lock{
    pointer-events:none;
}

Any hints of where to start? My game's here: http://jsfiddle.net/94jerdaw/WXEes/

EDIT:

Is it possible to navigate the div field as it is, going "up" from the current position or will i have to make a case for every div as an originating point accompanied by every div it should go to in up/down/left/right events?

like image 535
Dave Avatar asked Feb 17 '23 01:02

Dave


1 Answers

hope your question is still interesting to you. I had some time and I always want to have my own memory game. So I started building your desired functions, for full code see the Fiddle. Because of the fiddle frame you have to click once on the game.

Edit:Sorry there is some trash code in my script, because I forked one of my own basic setups for plugins, will remove it later.

It is not finished yet, but today I will finish it. I builded it as a plugin, because later on I want to add some options. But the idea of key movement should be clear.

I created a Map-Object (You can also use an array, easier I think) for finding positions.

Too much code to post it all here, so here a snippet:

$(window).keydown(function (e) {
    //Initial set first card as selected
    var actCard, nextCard;

    if ($('.cardset').find('.selected').length < 1) {
        $('#card1').addClass('selected');
    } else {
        switch (e.which) {
        case 37: // left
            $('.cardset').find('.selected').cardMoveHorizont('prev', cardMap);
            break;

        case 38: // up
            $('.cardset').find('.selected').cardMoveHorizont('up', cardMap);
            break;

        case 39: // right
            $('.cardset').find('.selected').cardMoveHorizont('next', cardMap);
            break;

        case 40: // down
            $('.cardset').find('.selected').cardMoveHorizont('down', cardMap);
            break;

        default:
            return; // exit this handler for other keys
        }
        e.preventDefault();
    }
});
like image 195
optimisticupdate Avatar answered Apr 28 '23 03:04

optimisticupdate