How to implement navigation between <span> using arrow keys?

I create my own combobox for a better design than a tag <select>.

By the way, I want to know how to make navigation using the arrow keys of the keyboard between <span>(or another <p>...) and display sentences using the "tab" key, Like a tag <option>tag <select>.

Here I would like to make it work:

HTML

<input type="text" id="myInput" value=""/>
<div id="myDiv">
    <span>Value 1</span>    
    <span>Value 2</span>
    <span>Value 3</span>
</div>

CSS

#myDiv {display:none;border:1px solid #000;}
span  {display:block;background:#EDEDED;cursor:pointer;}
span:hover {background:#555;color:#FFF;}

Js

$(document).ready(function(){
    $('#myInput').focus(function(){
        $('#myDiv').slideDown();
    });    

    $('span').click(function(){
         $('#myInput').val($(this).html());
         $('#myDiv').slideUp();
    });
});​

You can test it here: http://jsfiddle.net/eHpKX/2/

Editing example: for example, click or the input tab, and then use the arrow keys to navigate ... This does not work.

Any help would be appreciated.

+3
source share
1 answer

keydown uparrow downarrow, , drop down. tab , , prevtDefault. . , ,

DEMO

CSS

span.active {background:#555;color:#FFF;}

JS:

$(document).ready(function() {
    $('#myInput').focus(function() {
        if ($('#myDiv span.active').length == 0) {
            $('#myDiv span:first').addClass('active');
        }
        $('#myDiv').slideDown();
    }).focusout(function() {
        $('#myDiv').slideUp();
    });
    $('span').click(function() {
        $('#myInput').val($(this).html());
    }).mouseenter(function() {
        $('#myDiv span').removeClass('active');
    }).keydown(function(e) {
        alert(e.which);

    });

    //keydown event
    $('#myInput').keydown(function(e) {
        var $actvOpt = $('#myDiv span.active');
        if (e.which == 13) { //enter key
            if ($actvOpt.length != 0) {
                $(this).val($actvOpt.text());
                $('#myDiv').slideUp();
            }
            return;
        }

        var actvIndex = $actvOpt.removeClass('active').index();
        var optCount = $('#myDiv span').length;

        if (e.which == 40) { //keydown
            actvIndex += 1;
        } else if (e.which == 38) { //keydown
            actvIndex -= 1;
        }

        if (actvIndex < 0) actvIndex = optCount - 1;
        else if (actvIndex >= optCount) actvIndex = 0;

        $('#myDiv span:eq(' + actvIndex + ')').addClass('active');

        $actvOpt = $('#myDiv span.active');
        $(this).val($actvOpt.text());        
    });
});
+3

All Articles