Blog>
Snippets

Enhancing Accessibility in Column Ordering

Improve accessibility for column ordering by implementing keyboard navigation and ARIA attributes, making the feature usable for everyone, including those relying on screen readers.
const KeyCodes = { ENTER: 13, SPACE: 32 };
Defines key codes for ENTER and SPACE to be used for keyboard interaction.
function handleColumnHeaderKeyDown(event, columnId, moveColumn) {
  if (event.keyCode === KeyCodes.ENTER || event.keyCode === KeyCodes.SPACE) {
    // Prevent default to avoid scrolling on space press
    event.preventDefault();
    // Call the function responsible for moving the column
    moveColumn(columnId);
  }
}
Handles keydown event on column headers. If ENTER or SPACE is pressed, it calls 'moveColumn' with the columnId.
function addAccessibilityAttributes(columnHeaders) {
  columnHeaders.forEach(headerElement => {
    // Make the header focusable
    headerElement.setAttribute('tabindex', '0');
    // Define role as 'button' to imply interactivity
    headerElement.setAttribute('role', 'button');
    // Add aria-label to improve screen reader experience
    headerElement.setAttribute('aria-label', `Move ${headerElement.textContent} column`);
  });
}
Enhances column headers by making them focusable, setting their role to 'button', and adding an appropriate aria-label for screen readers.
columnHeaders.forEach(headerElement => {
  headerElement.addEventListener('keydown', (event) => handleColumnHeaderKeyDown(event, headerElement.dataset.columnId, moveColumn));
});
Attaches the keydown event listener to each column header, passing the columnId and the moveColumn function into the event handler.