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();
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With