JavaScript: Filter a Reading List Without a Framework
Build a topic filter with a native select element and a few lines of JavaScript. The original reading list remains usable if the script does not load.
Prepare a small list
Use this markup in a standalone HTML document. Every item declares its topic in a data attribute. The visible text stays useful on its own.
<label for="topic">Choose a topic</label>
<select id="topic">
<option value="all">All topics</option>
<option value="web">Web development</option>
<option value="server">Server</option>
</select>
<p id="result" role="status"></p>
<ul id="reading-list">
<li data-topic="web">Build a responsive reading card</li>
<li data-topic="server">Prepare your first Ubuntu VPS</li>
<li data-topic="web">Understand React state</li>
</ul>Respond to a change
Place this script immediately before the closing body tag. Query the controls once, then update each item when the selected topic changes.
const select = document.querySelector('#topic');
const items = [...document.querySelectorAll('#reading-list li')];
const result = document.querySelector('#result');
function filterItems() {
const topic = select.value;
let count = 0;
for (const item of items) {
const matches = topic === 'all' || item.dataset.topic === topic;
item.hidden = !matches;
if (matches) count += 1;
}
result.textContent = `${count} articles shown`;
}
select.addEventListener('change', filterItems);
filterItems();Why this stays small
The handler reads the current selection instead of keeping another copy of the topic in a variable. Each item is either visible or hidden. A status message reports how many remain, so the result is understandable without relying on a visual rearrangement alone.
textContent assigns text rather than interpreting it as HTML. That is the appropriate operation for this result message. If you later accept text from visitors, do not turn it into HTML merely to display it.
Try three checks
- Select Server. Exactly one item should remain.
- Select All topics. All three items should return.
- Use Tab and the arrow keys to change the select without a mouse.
To practice further, add a fourth entry with a new topic. Update the select options and confirm the count. Search, pagination, and a remote API can wait until the local interaction behaves correctly.
Komentar
Posting Komentar