Flying Turtle
Flying Turtle

Reputation: 364

trigger or return shift+tab in javascript or JQuery

I made a page for a windows CE with a two dimentional navigation using tabIndex. at first I just wanted to use tabIndex as a reference for the next focus.

because this application is for a portable device, doing it like this is very demanding on the handheld and very time consuming when comparing to a simple tab and shift+tab.

I have a function to process the onkeydown for my up arrow and down arrow, for my downarrow, the code is simple

if(specialMove == 0){all this does is checks that the tab isn't leaving the page.

event.keyCode=9; return;}

the problem is my uparrow, I want it to return a SHIFT+TAB to navigate upwards, I found this snipet of jQuery code but I'm having a problem making it work.

if(specialMove == 0){
    $('body').trigger(JQuery.Event('keydown', {keyCode:9, shiftKey: true}));
    return;
}

Upvotes: 2

Views: 7103

Answers (2)

user1629147
user1629147

Reputation: 1

const keyupEvent = new Event('KeyboardEvent');
keyupEvent.initEvent('keyup');
Object.defineProperties(keyupEvent, {
  keyCode: {
    value: 9
  },
  shiftKey: {
    value: true
  }
});

...

element.dispatch(keyupEvent);

Upvotes: 0

Kamiel Wanrooij
Kamiel Wanrooij

Reputation: 12404

Trigger only calls the event handlers defined on the body in this case. It does not send the key codes to the browser. See: http://api.jquery.com/trigger/. In short, it only executes the code that jQuery knows of that would be executed in case of a keydown event. It 'simulates' a keydown event.

Sending key events to the browser is not possible as far as I know, as this poses some serious security risks. You'll have to implement selecting the next and previous element in Javascript.

EDIT: You could try something like:

$(function() {
  var navigationElements = $('[tabIndex]').sort(function(a,b) {
    return $(a).attr('tabindex') - $(b).attr('tabindex');
  });

  // We don't know if the users presses the up or down button first
  // so we initialize as null and let the event handle the first element
  var currentIndex = null;

  // On event:
  if (currentIndex != null && currentIndex < navigationElements.length - 1) {
    navigationElements[++currentIndex].focus();
  } else {
    currentIndex = 0;
    navigationElements[currentIndex].focus();
  }

  // and:
  if (currentIndex != null && currentIndex > 0) {
    navigationElements[--currentIndex].focus();
  } else {
    currentIndex = navigationElements.length - 1;
    navigationElements[currentIndex].focus();
  }
});

This is untested, unoptimized code, so there probably is a much better solution but this would work pretty fast even on slow browsers. It does not take into account focus changes that do not go through your events, so you'd have to add onfocus events to set the currentIndex to the element that was lastly selected by the user.

Upvotes: 1

Related Questions