0

jQuery newbie here trying to figure out all the tricks of the keypress/trigger functions...

Essentially, I am trying to make the spacebar act as the tab key does, focusing on the next element with a specified tabindex in HTML.

Here's some sample HTML I might be using:

<div id="item_1" class="clickable" tabindex="1"></div>
<div id="item_2" class="clickable" tabindex="2"></div>
<div id="item_3" class="clickable" tabindex="3"></div>

Here's the jQuery I am trying to use now with no luck:

$('.clickable').keydown(function(e) {
    if (e.keyCode == 32) {
        e.which = 9;
        $(this).trigger(e);
    }
});

I did see this post already: Simulate Keypress With jQuery but didn't find it too helpful, maybe I am overlooking the basic concepts though. It seems like the solution there wasn't explicitly linking the actions of two different keys.

Community
  • 1
  • 1
user3542612
  • 11
  • 1
  • 3

1 Answers1

1

Try this:

$('.clickable').keydown(function(e) {
    if (e.keyCode == 32) {
        $(this).next().focus();
    }
});
elzi
  • 5,442
  • 7
  • 37
  • 61
  • Well, that sort of works. It'll now let me use the space bar to tab around the screen once and then stops unless I continue with the tab key. I also have to already be 'focused' on an element with a tabindex for this to do anything (meaning I can't just open the webpage and start space-barring away). This is because HTML tabindexes automatically loop back around when they reach the last one, including a stop in the url address bar. That's why I was hoping to trigger an actual tab keypress instead of just shifting focus. Any thoughts? – user3542612 Nov 19 '14 at 15:52
  • I thought you only wanted it for the `.clickable` classes. If you want it on the whole page, target `$(document)` instead – elzi Nov 19 '14 at 18:04
  • So when I tried the $(document).keydown... the spacebar no longer does anything, even when I'm already on a .clickable element – user3542612 Nov 19 '14 at 19:03
  • Hmmm... try some `if` conditionals on `$('[tabindex]').is(':focus')` – elzi Nov 19 '14 at 19:23