Created
August 15, 2013 22:47
-
-
Save glompix/6245668 to your computer and use it in GitHub Desktop.
Preserve tab order within Bootstrap tabbables.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* tab-order.js | |
Preserve tab order within Bootstrap tabbables. | |
*/ | |
(function ($) { | |
var _tabKeyCode = 9; | |
var _tabbableSelector = ':input:not([type="hidden"]),a[href]'; // Links can be tabbed to too! | |
function getTabbableElements($el) { | |
return $el.find(_tabbableSelector); | |
} | |
$(document).ready(function () { | |
// Pressing tab on the last element of a tab page should activate the next page | |
// and focus the first control on that page, or go to the next control outside of the | |
// tab set. Implement that last bit by just not applying this logic to the last tab | |
// page. filter(':input') is also pretty slow, so saves us some time searching the DOM. | |
$('.tab-pane:not(:last-child)').each(function () { | |
var $lastControl = getTabbableElements($(this)).filter(':last'); | |
$lastControl.keydown(function (e) { | |
if (e.keyCode === _tabKeyCode && !event.shiftKey && !event.ctrlKey) { | |
var $control = $(this); | |
var $tabPane = $control.closest('.tab-pane'); | |
// Traverse ancestors to find tab container, then find the tab button for this pane. | |
// Then, find the tab button for the *next* pane and show it. | |
var paneId = $tabPane.attr('id'); | |
var $controlTab = $tabPane.closest('.tabbable').find('a[href="#' + paneId + '"]'); | |
var $targetTab = $controlTab.closest('li').next().find('a'); | |
$targetTab.tab('show'); | |
} | |
}); | |
}); | |
// Pressing shift-tab on the first element of a tab page should activate the last page, | |
// or go tot he previous control outside of the tab set. | |
$('.tab-pane:not(:first-child)').each(function () { | |
var $firstControl = getTabbableElements($(this)).filter(':first'); | |
$firstControl.keydown(function (e) { | |
if (e.keyCode === _tabKeyCode && event.shiftKey) { | |
var $control = $(this); | |
var $tabPane = $control.closest('.tab-pane'); | |
// Traverse ancestors to find tab container, then find the tab button for this pane. | |
// Then, find the tab button for the *next* pane and show it. | |
var paneId = $tabPane.attr('id'); | |
var $controlTab = $tabPane.closest('.tabbable').find('a[href="#' + paneId + '"]'); | |
var $targetTab = $controlTab.closest('li').prev().find('a'); | |
$targetTab.tab('show'); | |
} | |
}); | |
}); | |
}); | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment