Smooth Tab Navigation Keys

User
on keyboard up and down arrow smooth display content from tab not on click
Assistant
To implement a feature where the content of tabs changes smoothly on pressing the up and down arrow keys, you can use JavaScript or Vue.js, depending on your setup. Here's an example implementation in plain JavaScript:

### HTML Structure

<div class="tabs-container" tabindex="0">
  <div class="tab" data-tab="1">Tab 1</div>
  <div class="tab" data-tab="2">Tab 2</div>
  <div class="tab" data-tab="3">Tab 3</div>
</div>

<div class="tab-content">
  <div class="content" data-content="1">Content for Tab 1</div>
  <div class="content" data-content="2">Content for Tab 2</div>
  <div class="content" data-content="3">Content for Tab 3</div>
</div>

### CSS for Smooth Transition

.tab-content .content {
  display: none;
  opacity: 0;
  transform: translateY(10px);
  transition: opacity 0.3s ease, transform 0.3s ease;
}

.tab-content .content.active {
  display: block;
  opacity: 1;
  transform: translateY(0);
}

### JavaScript for Key Navigation

document.addEventListener('DOMContentLoaded', () => {
  const tabsContainer = document.querySelector('.tabs-container');
  const tabs = Array.from(document.querySelectorAll('.tab'));
  const contents = Array.from(document.querySelectorAll('.tab-content .content'));

  let currentIndex = 0;

  const updateTabContent = (index) => {
    tabs.forEach((tab, i) => {
      tab.classList.toggle('active', i === index);
    });

    contents.forEach((content, i) => {
      content.classList.toggle('active', i === index);
    });
  };

  tabsContainer.addEventListener('keydown', (event) => {
    if (event.key === 'ArrowDown') {
      currentIndex = (currentIndex + 1) % tabs.length;
      updateTabContent(currentIndex);
    } else if (event.key === 'ArrowUp') {
      currentIndex = (currentIndex - 1 + tabs.length) % tabs.length;
      updateTabContent(currentIndex);
    }
  });

  // Initialize first tab as active
  updateTabContent(currentIndex);

  // Ensure tabs container is focusable
  tabsContainer.setAttribute('tabindex', '0');
});

### Key Points:
1. **Focusable Element**: The `tabs-container` div has a `tabindex="0"` to ensure it can receive keyboard focus.
2. **CSS Transition**: The `opacity` and `transform` properties ensure smooth transitions between tabs.
3. **Keyboard Event Listener**: The `keydown` event listens for arrow key presses to navigate tabs.

This approach allows smooth transitions between tabs when navigating using the up and down arrow keys. Let me know if you'd like an example in Vue.js or any other customization!

Leave a Comment

Your email address will not be published. Required fields are marked *