Skip to main content

AJAX Content

OpenKeyNav can be used effectively with dynamically loaded content via AJAX. This ensures that all newly added interactive elements are accessible through the keyboard.

This approach applies not only to vanilla JavaScript and AJAX but also to modern JavaScript frameworks such as React, Vue, and Angular. These frameworks often update the DOM dynamically, similar to AJAX. OpenKeyNav will automatically recognize new elements added by these frameworks on the next mode initiation, ensuring seamless keyboard accessibility without additional configuration.

Here’s how to configure OpenKeyNav to work with AJAX content.

Ensuring Accessibility for AJAX-loaded Content

When content is loaded dynamically via AJAX, OpenKeyNav does not need to be reinitialized to recognize the new elements. It will automatically recognize all new elements the next time a mode is entered. If it's in the middle of a mode, it won't recognize new elements until the next time the mode is initiated.

Example

Here's an example demonstrating how to use OpenKeyNav with AJAX-loaded content:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OpenKeyNav with AJAX Content</title>
<script src="https://cdn.jsdelivr.net/npm/openkeynav/dist/openkeynav.umd.min.js"></script>
</head>
<body>
<button id="loadContentBtn">Load More Content</button>
<div id="contentContainer">
<!-- Initial content here -->
</div>

<script>
// Initialize OpenKeyNav
const openKeyNav = new OpenKeyNav();
openKeyNav.init();

document.getElementById('loadContentBtn').addEventListener('click', () => {
// Simulate AJAX content loading
setTimeout(() => {
const newContent = `
<div class="new-content">
<button>New Button 1</button>
<button>New Button 2</button>
</div>
`;
document.getElementById('contentContainer').insertAdjacentHTML('beforeend', newContent);

// No need to update OpenKeyNav, it will recognize new elements on the next mode initiation
}, 1000); // Simulate network delay
});
</script>
</body>
</html>

Explanation

  1. Initialization: OpenKeyNav is initialized when the page loads.
  2. AJAX Content Loading: When the "Load More Content" button is clicked, new content is added to the contentContainer after a simulated network delay.
  3. Automatic Recognition: OpenKeyNav will automatically recognize the new elements the next time a mode is entered. If a mode is currently active, it will recognize the new elements when the mode is re-initiated.

Summary

OpenKeyNav simplifies handling dynamically loaded content by automatically recognizing new elements upon the next mode initiation. This approach helps maintain a seamless and accessible user experience as your content changes dynamically without requiring reinitialization.