JSFiddle - React, Tailwind, and code Playground
HTML
<input type="text" id="input1" value="input1" />
<input type="text" id="input2" value="input2" />
<input type="text" id="input3" value="input3" />
<div id="console" />
CSS
#input1 {
position: absolute;
top: 50px;
}
#console {
position: absolute;
bottom: 50px;
height: 150px;
}
.logEntry {
font-family: monospace;
color: blue;
}
JavaScript
function log (msg) {
var $console = $('#console');
var $entry = $('<p class=\"logEntry\"></p>');
$console.append($entry.text(msg));
}
function elmToString (elm) {
return elm.id;
}
function elmArrayToString (elmArray) {
return elmArray.map(function (elm) {
return elmToString(elm);
}).join(',');
}
var tabPressed = false;
var currentElms = $('input');
currentElms.on('keydown', function (event) {
tabPressed = event.which === 9;
});
currentElms.on('focusin', function (event) {
tabPressed = false;
});
currentElms.on('focusout', function (event) {
if (!tabPressed) {
return;
}
// fetch all currently visible input elements
var elms = $('input:visible').toArray();
log('currently visible elements, initial: ' + elmArrayToString(elms));
// sort input elements left-to-right, then top-to-bottom
elms.sort(function (a, b) {
return a.offsetLeft - b.offsetLeft;
});
elms.sort(function (a, b) {
return a.offsetTop - b.offsetTop;
});
log('currently visible elements, sorted: ' + elmArrayToString(elms));
// find index of current input element
var idx;
for (idx = 0; idx < elms.length; idx += 1) {
if (elms[idx] === event.target) {
break;
}
}
log('current element: ' + elmToString(event.target));
log('current element index: ' + idx);
// increment the index to reference next input element
idx += 1;
if (idx >= elms.length) {
idx = 0;
}
log('next element index: ' + idx);
// focus next input element
$(elms[idx]).focus();
log('next element focused: ' + elmToString(elms[idx]));
});