Tony
Tony

Reputation: 3299

Key event binding at table level

I have 2 tables on 1 page. I would like the user to be able to click the table and then use the arrow keys to navigate to previous and next. The only way I have been able to get the keyup events to fire in all browsers is by attaching them directly to the 'document'. I have wired up an event to add a 'grid-focused' class to the grid that is in focus and I tried using that as the selector on my events but I cannot get any event action then.

Event Binding

function attachInitEvents() {
    if ($self.config.pageHotKeysEnabled) {
        var keyNav = function(e) {
            if (e.keyCode == 37 && paging.hasPrevious) { // left
                $self._log.info('Left arrow key pressed.');
                fetchData('prev');
            }
            if (e.keyCode == 39 && paging.hasNext) { //right
                $self._log.info('Right arrow key pressed.');
                fetchData('next');
            }
        }
        var $doc = $(document);

        // hot key support
        $doc.off('keyup');
        $doc.on('keyup', keyNav);
    }
}

I am having another issue, where I am doing $doc.off('keyup'). I think this is part of the problem as it is unbinding all keyup events, what I really want is for it to just unbind the event I am trying to attach if it exists. In jQuery docs it technically says I should be using $doc.off('keyup', keyNav); to unbind it, but it does not unbind the event and I get multiples of it.

So core questions are,

  1. Can I trigger a KeyUp event without binding to the document and can I do it from the table level?
  2. How can I properly make sure I am not rebinding over and over again? Now, if this page has 2 tables, I guess I would expect there to be 2 events one for each table and then the .grid-focused class would be what allows the event to trigger or not?

Here is a Fiddle: http://jsfiddle.net/93fp293w/

Basically, I have no input boxes it is just spans, I am basically making it easier for them to page through all the data by just using the arrow keys. I believe the fiddler is pretty accurate to the situation. I feel what I am asking is not possible since I wont have an actual control in focus and if that is the case I can accept that but I guess I am hoping there is a work around.

Upvotes: 0

Views: 126

Answers (1)

DarthCoder
DarthCoder

Reputation: 354

The problem with attaching keyup is that, the parent div has to be mutable(contenteditable). else you have to attach to the document.

I have updated fiddle, might be a hack let me know if this works for you ?

http://jsfiddle.net/puneethp/qfpyeydg/3/

$(document).on("keyup", function (e) {
e.target = $(".focus")[0];
..
}

if you have only one column focused at a time, my previous fiddle will still work.

Upvotes: 1

Related Questions