smartyfy.mrindigi.com

Web Development Pro | Lesson 030 | JavaScript Project: Workshop Finder

Web Development Pro · Lesson 30 of 60

Module 3: JavaScript foundations

In this lesson

Prerequisites and learning outcomes

Complete lesson 29 first. This lesson builds on events, rendering, and form integration. By the end, you can build a searchable local workshop finder with coherent empty and reset states. Plan 10–15 minutes for the core explanation and additional time for the worked practice.

Build a complete local workshop finder

This project combines arrays, objects, functions, DOM creation, and events into a searchable workshop list. A visitor can enter a title fragment, submit the search, read the result count, and clear the search. All records are fictional and embedded locally. There are no accounts, remote requests, or real registrations.

Start from a fresh project folder or copy the supplied reference. Keep the search controls outside the result list so rerendering does not destroy the field being used. The initial HTML includes the full workshop list as a useful baseline, and the script replaces that list only after successful setup. If JavaScript fails to load, the basic workshop information remains readable.

Separate filtering from rendering

The pure filter function receives records and a query, trims surrounding whitespace, lowercases the query, and returns matching records. An empty normalized query returns a shallow array copy containing all records. It does not mutate the source collection. This gives the reset behavior a simple data contract.

function filterWorkshops(items, query) {
  const term = query.trim().toLowerCase();
  return term === '' ? [...items] : items.filter(item =>
    item.title.toLowerCase().includes(term));
}

For this English demonstration, substring matching is enough. A search for bike does not match Bicycle basics because those exact letters do not occur consecutively in bicycle. That is a feature of the chosen rule, not necessarily a bug. If users need synonyms or word-stem matching, define that as a new requirement rather than silently changing the current contract.

The complete app.js also defines the three records and the renderer. The renderer creates li, h2, and p elements with textContent, replaces the list children, updates a singular-or-plural result count, and shows an empty message when needed. All helpers are supplied in the same file; the excerpt does not depend on hidden utility functions.

Connect one-time event handlers

The form contains a labeled input named q and a submit button. A separate type="button" control clears the query. Submit prevents the local form's normal navigation and renders the filtered records. Reset assigns an empty string, renders all records, and returns focus to the query because the user explicitly requested a fresh search.

form.addEventListener('submit', event => {
  event.preventDefault();
  renderWorkshops(filterWorkshops(workshops, query.value));
});
reset.addEventListener('click', () => {
  query.value = '';
  renderWorkshops(filterWorkshops(workshops, ''));
  query.focus();
});
renderWorkshops(workshops);

These lines follow the visible helper definitions and element guards in the full example. Listener setup happens once. Render does not attach more listeners or replace the form. This prevents repeated searches from multiplying handlers or losing the text field's identity.

Define the empty and reset states

A zero-result search shows an explicit message suggesting a different term or clearing the search. It also shows zero in the status count and removes old rows. Keeping stale rows while displaying a zero count would create contradictory evidence. The view should be one coherent representation of the current result set.

Reset restores all three records, clears the input, hides the empty message, and updates the count. It does not reload the page or alter the source records. Repeated reset clicks should leave the same state, which is a useful idempotence property: applying the reset again has no additional effect beyond the intended baseline.

Search happens on submit rather than every keystroke in this version. That keeps the interaction simple and avoids announcing a new count on each character. Live filtering can be useful, but it requires deliberate decisions about timing, announcements, input methods, and performance. A later enhancement should be justified by the task, not added automatically.

Keep the interface semantic and safe

The input has a visible label, the results remain a real list, and each result uses a heading under the page h1. The count is a short polite status region. Links and buttons keep their native semantics. Do not turn the entire page into a live region or add positive tabindex values to force a custom reading order.

Titles are inserted with textContent, including any markup-like characters. The filter operates on strings but does not produce HTML. This separation keeps data from deciding document structure. If later records include URLs, dates, or rich text, each new field needs an explicit validation and rendering policy rather than inheriting an assumption that every string is safe everywhere.

Test the journey and its boundaries

The automated cases search for BICYCLE, a whitespace-padded term, no match, and an empty query. They test repeated submits, reset after zero results, and a title containing markup-like text. They check the pure filter separately from the event-to-render path so a failed result can be localized.

The DOM fixture models only the methods the example uses. It invokes handlers directly and observes children, text, visibility, and a modeled focus call. It does not implement browser layout, native keyboard submission, live-region announcements, or real focus navigation. Static HTML checks verify the actual ids and files, while those browser behaviors remain explicit manual gates.

Prepare the next milestone

Write a README explaining how to open index.html, the exact search rule, the fictional data, and the checks still needed. Keep the data, filtering, rendering, and event wiring visually separated in app.js even before you split them into modules. This makes the next lesson's file boundaries a natural refactor rather than a rescue operation.

The result is a complete local implementation with tested language and modeled DOM behavior. Do not call it externally deployed or fully browser-verified. In the next unit, the same directory will load local JSON over HTTP, handle failure, and preserve shareable filter state without losing the clear contracts established here.

Worked practice

Worked exercise 1: Explain an unexpected no-match

Task: A learner searches bike and expects Bicycle basics. Worked answer: the implemented rule is literal case-insensitive substring matching, and bike is not a substring of bicycle. Search bicycle or change the documented requirement to support synonyms, with new tests for that behavior.

Worked exercise 2: Test a full recovery path

Task: Search an unmatched word, then press Clear search. Worked answer: first expect zero rows and a visible empty message; afterward expect all three rows, an empty query, a hidden empty message, and the count restored. Checking only the successful initial search would miss this recovery journey.

Worked exercise 3: Preserve input focus during results

Task: Rerendering replaces main and removes the search field. Worked answer: narrow renderer ownership to the result list and status elements. Keep the form stable so typing and focus are not destroyed by an unrelated result update.

Knowledge check

Question 1

What does the filter promise for an empty normalized query? A) All records in a new outer array. B) The original array reference without a copy. C) An empty array because the query contains no search characters. D) All records after removing nonmatches from the input array.

Check question 1: answer and explanation

Answer: A. Empty search means the unfiltered collection while preserving the input array.

Question 2

Why keep controls outside the replaced results? A) To avoid reattaching listeners while still replacing the controls themselves. B) To preserve their identity and interaction state. C) To let every render reset their entered values to HTML defaults. D) To transfer their old listeners automatically to newly created elements.

Check question 2: answer and explanation

Answer: B. Result rendering should not destroy the controls driving it.

Question 3

Which outcome makes reset coherent? A) Clear text but retain stale filtered rows. B) Restore rows but retain the zero-result message. C) Clear query, restore all rows, and synchronize count and empty state. D) Restore the rows while keeping the previous result count.

Check question 3: answer and explanation

Answer: C. The visible state should agree across all related elements.

Question 4

Why is bike not guaranteed to match Bicycle basics here? A) The search is case-sensitive. B) The rule removes all whitespace from the title before comparison. C) The rule matches the category rather than the title. D) The rule uses exact substrings rather than synonyms.

Check question 4: answer and explanation

Answer: D. Search behavior follows its explicit text-matching contract.

Question 5

What remains after passing the provided modeled integration tests? A) Real browser keyboard, rendering, and assistive-technology checks. B) Treat modeled focus assignment as a verified keyboard journey. C) Treat the presence of role=status as an observed announcement. D) Treat matching ids as proof of native form submission behavior.

Check question 5: answer and explanation

Answer: A. Runtime doubles provide useful evidence without covering the full browser experience.

Sources and further reading