By the end of this lesson, you will understand how to improve keyboard access, safely output text, and enhance search performance in your JavaScript applications.
Imagine using a shopping website. You might want to search for shoes. If the search bar is hard to reach or shows unsafe text, you may leave the site. Therefore, improving keyboard access and safe text output helps users stay longer and engage more.
Improving keyboard access is crucial for users who cannot use a mouse. Make sure all interactive elements can be accessed by keyboard alone. Use tabindex to set the order of focusable elements. This change makes navigation easier for all users.
When displaying user input, always sanitize it to prevent attacks like Cross-Site Scripting (XSS). You can use JavaScript’s built-in functions, such as textContent, to safely display text. As a result, this keeps users connected to your site.
To enhance keyboard accessibility further, ensure that the visibility of all elements is clear. When users navigate, they should know where they are. Additionally, use clear focus indicators to enhance their experience.
Enhancing search performance can speed up user queries. For example, consider using indexing or caching search results. This approach reduces the time it takes to find relevant data. Also, it helps users find what they need quickly.
File: search.js
// Sample search function with safe output
const searchItems = (query, items) => {
const results = items.filter(item => item.includes(query));
return results.map(item => {
const safeText = document.createElement('div');
safeText.textContent = item; // Safe text output
return safeText;
});
};
const items = ['Shoes', 'Shirts', 'Socks'];
console.log(searchItems('Sho', items));
[<div>Shoes</div>]
The line return results.map(item => { creates a new array of elements that will be safely displayed. The use of textContent ensures that any HTML tags in the item are not executed in the browser.
Create a simple search function for a list of your favorite fruits. Ensure it safely displays the results and can be accessed via keyboard.
// Example solution for fruits search
const searchFruits = (query, fruits) => {
const results = fruits.filter(fruit => fruit.includes(query));
return results.map(fruit => {
const safeText = document.createElement('div');
safeText.textContent = fruit; // Safe text output
return safeText;
});
};
const fruits = ['Apple', 'Banana', 'Cherry', 'Date'];
console.log(searchFruits('a', fruits));
textContent instead of innerHTML.tabindex appropriately.