Skip to content

Commit

Permalink
Add arrow key navigation for tabs; Autoselect tab on arrow key naviga…
Browse files Browse the repository at this point in the history
…tion; Fix tab to stop only once in tablist
  • Loading branch information
datakurre committed Aug 17, 2024
1 parent 8ec736b commit d375a6d
Showing 1 changed file with 22 additions and 8 deletions.
30 changes: 22 additions & 8 deletions src/sphinxcontrib/httpexample/static/sphinxcontrib-httpexample.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ document.addEventListener("DOMContentLoaded", function() {
}

// Process each caption element
captions.forEach(function(caption) {
captions.forEach(function(caption, index) {
var orphan, block = !!caption.parentElement.id ? caption.parentElement : caption.parentElement.parentElement;
block.setAttribute('role', 'tabpanel');
block.setAttribute('tabindex', '0');
Expand All @@ -32,16 +32,20 @@ document.addEventListener("DOMContentLoaded", function() {

// Click event for captions
caption.addEventListener('click', function() {
// Deselect other captions
captions.forEach(function(otherCaption) {
otherCaption.setAttribute('aria-selected', 'false');
otherCaption.classList.remove('selected');
if (caption === otherCaption) {
// Select the clicked caption
caption.setAttribute('aria-selected', 'true');
caption.classList.add('selected');
otherCaption.setAttribute('tabindex', '0');
} else {
// Deselect other captions
otherCaption.setAttribute('aria-selected', 'false');
otherCaption.setAttribute('tabindex', '-1');
otherCaption.classList.remove('selected');
}
});

// Select the clicked caption
caption.setAttribute('aria-selected', 'true');
caption.classList.add('selected');

// Hide other blocks and show the selected one
blocks.forEach(function(otherBlock) {
if (otherBlock !== block) {
Expand All @@ -57,6 +61,16 @@ document.addEventListener("DOMContentLoaded", function() {
caption.addEventListener('keydown', function(event) {
if (event.code === 'Space' || event.code === 'Enter') {
caption.click();
} else if (event.code === 'ArrowRight') {
// Move focus to the next tab
var nextIndex = (index + 1) % captions.length;
captions[nextIndex].focus();
captions[nextIndex].click();
} else if (event.code === 'ArrowLeft') {
// Move focus to the previous tab
var prevIndex = (index - 1 + captions.length) % captions.length;
captions[prevIndex].focus();
captions[prevIndex].click();
}
});

Expand Down

0 comments on commit d375a6d

Please sign in to comment.