Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to programmatically trigger the TAB key to move the focus to the next focusable element? [duplicate]

I am writing a unit test to test the tab order on my webpage and I could not find a way to simulate the user's keying down of the TAB key to focus on the next focusable element, though this seems to be an easy task.

jQuery is allowed while pure javascript solution is preferred. Any kind of help is appreciated.

// TODO
function triggerTab () {


}

$("#btn-save").focus();
triggerTab();

// Expect the focus is on the cancel button now.
console.log(document.activeElement.id);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p> some text </p> 
<button id="btn-save"> save </button>
<button id="btn-cancel> cancel </button>

P.S. It is no acceptable to call focus() on the next focusable element, even if you can write code to figure out the next focusable element. So this path is NOT what I want:

function getAllFocusables () {
    ...
}

var focusables = getAllFocusables(),
    index = focusables.indexOf(document.activeElement);

$(focusables[index+1]).focus();
like image 811
Jason Lee Avatar asked Nov 06 '16 21:11

Jason Lee


People also ask

How do I set the focus on my Tabindex?

tabindex is a global attribute that allows an HTML element to receive focus. It needs a value of zero or a negative number in order to work in an accessible way. When tabindex 's value is set to zero or a positive number, the element can be navigated to via the keyboard's Tab key.

How do I turn off tab focus?

Solution with the tabindex attribute To prevent tab indexing on specific elements, you can use tabindex="-1". If the value is negative, the user agent will set the tabindex focus flag of the element, but the element should not be reachable with sequential focus navigation.


1 Answers

You can not simulate a tab key from a standard browser using Javascript.

If you are doing your unit test using a headless browser, like phantomjs for instance, you can emulate the tab key

var webPage = require('webpage');
var page = webPage.create();

page.sendEvent('keypress', page.event.key.Tab);
like image 80
Adam Avatar answered Nov 03 '22 01:11

Adam