Pergunta

I'm interested in using JS events such as right\left arrow, space bar etc. Wondering what's the right way to do it. I would like to slide photos, make DIVs appear etc. on such user interactions.

I thought of possible implementations with jQuery such as http://api.jquery.com/event.which/ Though I'm not sure that's the best way.

Here are two good examples for such UI implementations (How do they do it?) http://www.thesixtyone.com ; http://www.pictorymag.com/showcases/summer-jobless

I'm more a c# kinda guy, looking for the right direction to dig in. Thanks.

Foi útil?

Solução

If you're already using jQuery or plan to, taking advantage of which is not a bad idea. If you look at the example, it shows you exactly how to do it. Put your cursor in the text field there and press the key that you're interested in, i.e. left arrow. The number that is displayed in keydown: is the code you're looking for.

Now, when you write your own function, you might bind keydown to the document and listen for the correct keys. From there, you can dispatch certain behaviors depending on which key was pressed.

$(document).bind('keydown', function (e) {
    var code = e.which;
    switch (code) {
        case 39:
            // code to execute when right arrow is pressed
            some_right_arrow_action();
            break;
        case 37:
            // code to execute when left arrow is pressed
            some_left_arrow_action();
            break;
    }
    return;
});

You asked how sites like Pictorymag.com handle this functionality. Here's what Pictorymag.com does (I've decompressed their code to make it easier to read):

$(document).keydown(function (e) {
    switch(e.keyCode) {
        case 39:
        case 74:
            node = s[++curr];
            if(node) {
                $.scrollTo(node,800);
            } else {
                curr = s.length-1;
            }
            break;
        case 37:
        case 75:
            node = s[--curr];
            if (node) {
                $.scrollTo(node, 800);
            } else {
                curr=0;
            }
            break;
    }
});
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top