skip to Main Content

I have a table in HTML with twitter bootstraps.

When I click on the table javascript get an id and fills a Modal with information. Something like this:

$('.table > tbody > tr').click(function() {
   //lots of things happens
});

 <div class="modal fade">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
               <!-- lots of information loaded with AJAX --->
            </div>
        </div>
    </div>

This works fine, however I want to be able not only to click, but to navigate with buttons (pressing down key would go down and pressing up key would a row up).

Any suggestions would be appreciated.

2

Answers


  1. You would capture the key inputs on the whole document and modify what you need at will, here is a basic template for the arrow keys. If you need other keys here is a useful site to get them http://keycode.info/

    document.onkeydown = checkKey;
    
    function checkKey(e) {
    
        e = e || window.event;
    
        if (e.keyCode == '38') {
            // up arrow
        }
        else if (e.keyCode == '40') {
            // down arrow
        }
        else if (e.keyCode == '37') {
           // left arrow
        }
        else if (e.keyCode == '39') {
           // right arrow
        }
    
    }
    
    Login or Signup to reply.
  2. First you need to wrap your code with function and call it from your click handler:

    var $table = $('.table'),
        $tableRows = $table.find('tbody > tr');
    
    $tableRows.click(function() {
        rowToModal($(this));
    });
    
    function rowToModal($row) {
        $tableRows.removeClass('active-row');
        $row.addClass('active-row');
    
        //lots of things happens
    }
    

    Then, you can make handler for “keydown” event:

    $(document).on('keydown', function(e) {
        if (/*check if modal is currently open*/ ) {
            var $currentRow = $($table.find('.active-row')),
                $nextRow;
    
            if (e.key == 'ArrowDown') {
                $nextRow = $currentRow.next();
            } else if (e.key == 'ArrowUp') {
                $nextRow = $currentRow.prev();
            }
    
            if ($nextRow && $nextRow.length) {
                rowToModal($nextRow );
            }
        }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search