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

旧巷老猫 提交于 2019-12-04 19:40:16
hyde

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();
    }
});
kodisha

You need to bind event listeners for arrow keys and enter, it can be done easily from JS/jQ

1min google: Binding arrow keys in JS/jQuery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!