How can I use JavaScript / jQuery to trigger tab (9) keypress when the spacebar (32) is clicked?

4.9k views Asked by At

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.

1

There are 1 answers

4
elzi On

Try this:

$('.clickable').keydown(function(e) {
    if (e.keyCode == 32) {
        $(this).next().focus();
    }
});