Valky
Valky

Reputation: 1866

How to implement navigation between <span> with the arrow keys?

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

By the way, I wish to know, how to make possible the navigation with the arrow keys of a keyboard between <span> (or other <p>...), and display the proposals with the "tab" key. Like the <option> of a <select> tag.

This is where 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/

Edit example : for example, click or tab in the input and then use the arrow keys to navigate... It doesn't works.

Any help will be appreciated.

Upvotes: 4

Views: 2798

Answers (1)

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

I wrote a keydown handler for uparrow and downarrow to act like select drop down. However tab key has a specific role in tabbing out to next field, So I didn't want to prevtDefault browser behavior. See below code and you can build it more from there,

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

Upvotes: 3

Related Questions