Zum Inhalt springen

English:JavaScript fundamentals for interactive web pages - Computing Year 8

Aus MOOCsWiki Staging
aiMOOC-Siegel aiMOOC

JavaScript fundamentals for interactive web pages - Computing Year 8

QR-Code



Introduction

Build an original even-or-odd web interaction with a labelled field, real event handler and explicit input validation. Compare JavaScript decisions with familiar Python ideas and test both calculation and interface. Year 8 sequencing is editorial within England’s KS3 Computing pathway.


Separate structure, styling and JavaScript behaviour

Web structure, presentation and behaviour have different jobs. HTML defines elements such as headings, labels, form fields and buttons. CSS describes how those elements look and lay out. JavaScript can respond to events, make decisions and change the document. A browser represents the page as a document object model, or DOM, which the program can work with. Changing a button's colour does not create the number-checking algorithm, and writing a conditional does not by itself provide a clear label for a user.

The original project is a tiny even-or-odd checker. A user types a whole number, activates a button or presses Enter, and receives a textual result. No account, score submission or network connection is part of its logic. We separate a pure classification function from a DOM event handler. That makes the number rule testable without needing to click the interface for every calculation.

HTML5 logo identifies the document-structure technology
The unchanged W3C HTML5 logo is an explanatory illustration, not an endorsement or proof that every page using it is accessible or correct. Our JavaScript creates standard semantic HTML elements in a fresh preview document.

{| class="wikitable"

! Role !! Original project example !! What it does not establish |- | HTML structure || Label, text input, form and submit button || Not the even-or-odd calculation |- | CSS presentation || Spacing, readable font and useful control size || Not input validation |- | JavaScript behaviour || Read, validate, classify and display on submit || Not automatic correctness or user testing |- | DOM interface || Create and update the document elements || Not a separate replacement for HTML semantics |} Use const for a name that will not be reassigned and let for a name whose binding changes. A const binding does not make every object assigned to it deeply immutable. For example, a button can have properties set even when the variable holding it is const. The valid-check counter later uses let because its numerical value is reassigned after each successful check.

JavaScript strings and numbers remain different types. The text '14' arrives from the field as text; Number can convert it to a number. Strict equality, written with three equals signs, compares without the type coercion performed by the two-equals operator. Thus the number fourteen and text '14' are not strictly equal, even though loose equality can convert them for a comparison. The percent operator calculates remainder; a whole integer is even when its remainder on division by two is zero.

Programming with Mosh's original beginner course supports variables, types and operators. It is optional supporting material rather than a promise of mastering JavaScript in the thumbnail's advertised time. The original form, validation contract and complete written learning route are specified here. Original: Programming with Mosh, JavaScript Course for Beginners – Your First Step to Web Development. The written explanations and native tasks work without sound or the external player. Python has related computational ideas but different syntax. Its if statement uses a colon and indentation; JavaScript commonly uses parentheses around the condition and braces around the branch. Python's double equals tests equality, while this JavaScript example deliberately uses strict triple equals. Do not translate punctuation mechanically without checking each language's semantics. A small second-language comparison contributes to KS3 learning, not an automatic certificate of a complete multi-language project.



Validate numbers and use explicit decisions

Convert deliberately and reject ambiguous input. The original checker accepts a string containing decimal digits, an optional leading plus or minus, and optional surrounding whitespace. Its numerical value must be a whole integer from minus one thousand through one thousand inclusive. These are invented learning-interface rules. Decimal points, exponent notation, hexadecimal spelling and an empty field are rejected, even where JavaScript's general Number conversion would accept some of them.

function classifyWholeNumber(raw) {
  const error = {ok: false, message: "Enter a whole decimal number from -1000 to 1000."};
  if (typeof raw !== "string") return error;
  const text = raw.trim();
  if (!/^[+-]?\d+$/.test(text)) return error;
  const value = Number(text);
  if (!Number.isInteger(value) || !(value >= -1000 && 1000 >= value)) return error;
  return {ok: true, value: value, label: value % 2 === 0 ? "Even" : "Odd"};
}

The early error returns leave no valid numerical result for callers to mistake for a successful check. trim removes surrounding whitespace. The small regular expression accepts one optional sign followed by one or more decimal digits, and anchors the match to the entire trimmed string. Number then performs the conversion. Number.isInteger and the two range comparisons enforce the announced numerical contract. No text is executed as code.

Why check the text before conversion? Number of an empty string or a string containing only whitespace is zero. Without the separate empty/grammar check, a missing answer could be reported as an even zero. Number can also accept an exponent such as '1e2', but this interface intentionally asks for ordinary decimal whole-number spelling. A numeric-looking input is not automatically a permitted input under a particular contract.

For '14', conversion produces fourteen and the remainder is zero, so the returned object has ok True in JavaScript's lowercase spelling, value fourteen and label Even. For '9', the remainder is one and the label Odd. Negative three has a negative remainder in JavaScript but it is still nonzero, so the label remains Odd. Zero is even. The accepted spelling '-0' displays as zero; it does not create a distinct odd value.

Input text Expected outcome Reason
14 Even Accepted integer and zero remainder
9 Odd Accepted integer and nonzero remainder
0 or -0 Even Zero is divisible by two
An empty string or spaces Validation message Missing is not an observed zero
3.0 or 1e2 Validation message Not the accepted decimal-digit grammar
1000 or -1000 Even Allowed endpoints
1001 or -1001 Validation message Outside the permitted range

The returned object separates a success flag, numerical value and display label. A failed result has an explanatory message instead. Callers must check ok before trying to use the label. This is clearer than silently returning zero on every error. Strict equality prevents unwanted comparison coercion; it does not replace the grammar, integer or range checks.

CSS3 logo identifies the presentation technology
This unchanged CSS3 logo illustrates styling as a separate concern. The original example uses CSS properties through the DOM style interface; its validation remains JavaScript logic and its labels remain semantic document elements.

Keep validation and user feedback aligned. If the limit changes, update the field label, helper text, pure function and tests together. Otherwise the page may invite a value its own algorithm rejects. Using textContent for the displayed result treats content as text, rather than interpreting entered characters as document markup. No real learner data is required to test any of these cases.



Build, operate and test the complete interaction

Make the event handler small and the whole interaction usable. Run the two complete JavaScript blocks, first the classification function and then the interface below, in a fresh approved JavaScript web preview. The interface creates its own document elements, so an initially empty HTML preview body is sufficient. In a school-approved editor with separate HTML, CSS and JavaScript panes, place both blocks in the JavaScript pane and run the preview; do not paste them into unrelated websites, the MOOCwiki page console or an existing account page.

A local alternative is a standard HTML starter document whose body loads your saved JavaScript file. Use your editor's ordinary starter/preview workflow, keep the script after the body exists and save both complete blocks in that file. The course presents source code for learners to run; the wiki does not execute the displayed source as a live replacement for its own interface. If no editor is available, trace the same sequence on paper and identify the missing practical execution evidence.

(() => {
  const root = document.createElement("main");
  const title = document.createElement("h1");
  title.textContent = "Even or odd?";
  const form = document.createElement("form");
  const label = document.createElement("label");
  label.htmlFor = "whole-number";
  label.textContent = "Whole number from -1000 to 1000";
  const input = document.createElement("input");
  input.id = "whole-number";
  input.type = "text";
  input.inputMode = "numeric";
  input.maxLength = 16;
  input.setAttribute("aria-describedby", "number-hint");
  const hint = document.createElement("p");
  hint.id = "number-hint";
  hint.textContent = "Use decimal digits, with an optional leading plus or minus. Empty is not zero.";
  const check = document.createElement("button");
  check.type = "submit";
  check.textContent = "Check number";
  const clear = document.createElement("button");
  clear.type = "button";
  clear.textContent = "Clear";
  const result = document.createElement("p");
  result.id = "number-result";
  result.setAttribute("role", "status");
  result.setAttribute("aria-live", "polite");
  result.textContent = "Enter a number, then choose Check number.";
  const counter = document.createElement("p");
  let checked = 0;
  counter.textContent = "Valid checks: 0";
  form.addEventListener("submit", (event) => {
    event.preventDefault();
    const answer = classifyWholeNumber(input.value);
    if (!answer.ok) {
      result.textContent = answer.message;
      return;
    }
    checked += 1;
    result.textContent = answer.value + " is " + answer.label + ".";
    counter.textContent = "Valid checks: " + checked;
  });
  input.addEventListener("input", () => {
    result.textContent = "Input changed. Choose Check number again.";
  });
  clear.addEventListener("click", () => {
    input.value = "";
    checked = 0;
    counter.textContent = "Valid checks: 0";
    result.textContent = "Enter a number, then choose Check number.";
    input.focus();
  });
  Object.assign(root.style, {maxWidth: "42rem", margin: "2rem auto", padding: "1rem", boxSizing: "border-box", fontFamily: "system-ui, sans-serif", color: "#17364b"});
  Object.assign(form.style, {display: "grid", gap: "0.75rem"});
  Object.assign(input.style, {width: "100%", maxWidth: "24rem", minHeight: "44px", boxSizing: "border-box", fontSize: "1rem"});
  for (const button of [check, clear]) {
    Object.assign(button.style, {minHeight: "44px", fontSize: "1rem", padding: "0.5rem 1rem"});
  }
  form.append(label, input, hint, check, clear, result, counter);
  root.append(title, form);
  document.body.append(root);
})();

Submitting the form by its button or Enter invokes one registered submit handler. preventDefault stops the form's ordinary navigation. The handler reads input.value, calls the pure function and either shows the validation message or updates the result and increases the local valid-check counter. The input event marks an old result as stale when text changes. Clear empties the field, resets the local counter and returns focus to the labelled input. The counter records valid checks in this preview session; it is not a correctness score or MOOCwiki learning point award.

The label is explicitly associated with the input. Helper text explains the accepted spelling. The result has a status role with a polite live-region setting so assistive technology can be notified; actual announcements still depend on browser and assistive-technology combinations. Native buttons support keyboard activation, and visible words convey success or failure without relying on colour. Styling gives controls at least forty-four pixels height and keeps the input within a narrow viewport. These choices help usability but do not by themselves certify universal accessibility.

Use the following finite loop for a separate console comparison after defining classifyWholeNumber. It should display fourteen Even, nine Odd, zero Even and negative three Odd. The printed labels are predictions until you actually run them. The loop has a clear finite collection, unlike an unbounded repeated prompt that could trap a learner.

const examples = ["14", "9", "0", "-3"];
for (const text of examples) {
  const answer = classifyWholeNumber(text);
  console.log(text, answer.label);
}

Compare this short Python branch, using an already validated numerical value, with the JavaScript condition. The Python version alone is not the complete web form or its input-validation contract.

value = 14
if value % 2 == 0:
    label = "Even"
else:
    label = "Odd"

The exact original classifier was actually tested for every allowed integer and several accepted text spellings, plus empty, malformed and out-of-range inputs. Its real DOM handlers were also exercised with button, keyboard and narrow-screen touch interactions. These author tests do not mean every browser, assistive technology or learner has been tested. Keep your own expected-versus-actual results and distinguish pure-function tests from actual user-interface events.

Corey Schafer: Python functions provide an explicit comparison with the second textual language. Python syntax does not substitute for the JavaScript event handler.

For transfer, ask a known user to try the preview where school arrangements permit. Record consent-appropriate anonymous observations such as whether they find the input and understand the error, not their personal details. Until a real user tries it, call an author walkthrough a simulation. Improve labels or layout from evidence, rerun the same behavioural tests, and retain the source artefact. This small interaction contributes to broader creative-project objectives; it is not the complete multi-application, multiple-device project on its own.



Interactive Tasks


Quiz: Test Your Knowledge

Which role does HTML mainly provide in the original form? (Document structure and semantic controls) (!The numerical even-or-odd calculation) (!Automatic proof that every input is valid) (!The same job as every CSS colour property)



Why does the original valid-check counter use let? (Its numerical binding changes after successful checks) (!Every DOM element must use let to receive text) (!const is forbidden in browser JavaScript) (!let automatically persists values to a server)



What does strict equality avoid compared with loose equality? (Implicit type coercion during that equality comparison) (!The need for every other validation rule) (!All possible programming errors and incorrect assumptions) (!Any distinction between text and a number)



Why reject an empty or whitespace-only entry before Number conversion? (Number can otherwise convert missing text to zero) (!An empty string always converts to the number one) (!Every empty field proves that the learner chose an even integer) (!Whitespace is required to select the Odd branch)



What does the original classifier return for fourteen? (A successful result with value fourteen and label Even) (!A failed result because all two-digit inputs are invalid) (!Odd because fourteen is stored initially as text) (!A real MOOCwiki point award for fourteen points)



How is negative three classified under the original remainder test? (Odd because its remainder is nonzero) (!Even because every negative remainder counts as zero) (!Invalid because the model permits only positive numbers) (!A clock time because the sign changes the unit)



Which input is rejected by the stated decimal-digit interface? (The exponent spelling 1e2) (!A sign followed by fourteen) (!The endpoint one thousand) (!Ordinary decimal zero)



What causes the registered submit handler to run? (Submitting the form with its button or Enter) (!Merely declaring the handler before any interaction) (!Changing only the CSS background colour) (!Waiting until an external account approves the result)



Why use textContent for the displayed message? (It treats the assigned content as text rather than document markup) (!It executes entered text as JavaScript automatically) (!It bypasses the input grammar for every valid-looking value) (!It sends the result to the public leaderboard)



What does a complete practical submission require here? (Runnable source and actual event and input tests with expected results) (!Only the logo of one web technology) (!A paper prediction labelled as a browser execution) (!A claim of full accessibility without testing any interaction)





Memory Game

HTML Document structure and semantic elements
CSS Presentation and layout rules
JavaScript Programmable behaviour and decisions
Event handler A function registered to respond to an event
Strict equality Equality comparison without type coercion
DOM A programmable representation of the document





Drag and Drop

An empty field becomes even zero after unguarded conversion Check missing or malformed text before interpreting it as a number
A changed field still displays its previous classification Mark the old result stale and require a fresh check
The number and text fourteen are compared Distinguish strict equality from converting loose comparison
A form navigates away instead of showing its local result Handle submission and prevent its default navigation
A label is visually nearby but not associated with the field Connect the label to the input and test keyboard operation





Crossword Puzzle

EVENT What occurrence can trigger a registered response?
HANDLER What function responds to an occurrence?
STRING What type arrives from the text field?
NUMBER What type is needed for the remainder calculation?
STRICT What kind of equality avoids comparison coercion?
BOOLEAN What type expresses a true-or-false condition?





LearningApps

Optional extra practice. Choose an appropriate activity with your teacher. If the external collection is unavailable, use the native activities and independent tasks in this course.


Cloze Text

Complete the explanation.
HTML supplies document

. CSS controls

. JavaScript adds programmable

. An input field supplies a

. Number attempts numerical

. Empty text must not silently count as observed

. A whole even integer has zero

on division by two. The form registers an event

. The counter increases only after a

check. A paper trace is not actual browser

.



Open Tasks


Easy

  1. Name the three roles: Identify structure, styling and behaviour in the original checker.
  2. Trace two values: Follow fourteen and nine from text input through conversion, remainder and displayed label.
  3. Explain missing input: Predict Number on empty text, then explain why this checker rejects it.
  4. Compare equality: Contrast numerical fourteen with text fourteen using strict and loose equality.


Standard

  1. Run the full interface: Create a fresh approved preview, load both complete JavaScript blocks and test button and Enter submission.
  2. Test boundaries: Record expected and actual outcomes for zero, negative three, both allowed endpoints and both values just outside them.
  3. Compare languages: Translate the simple already-validated Python branch into JavaScript and explain its punctuation and equality operator.
  4. Audit feedback: Test an invalid value, a corrected value, changed input after success and Clear; explain the local valid-check counter.


Advanced

  1. Separate test levels: Create pure-function tests and real DOM-event tests, explaining what one cannot establish about the other.
  2. Revise the contract: Change the integer range while keeping grammar, labels, helper text and tests consistent.
  3. Evaluate usability: Test labels, keyboard operation, narrow viewport and text feedback; report actual observations and remaining assistive-technology uncertainty.
  4. Meet a known user need: Where school arrangements allow, collect minimal anonymous feedback from an actual user and improve the preview; identify simulations honestly if no real user test occurred.



Learning Check

  1. Technology roles and bindings: Explain the project components.
  2. Conversion and validation: Apply the original input contract.
  3. Remainder and comparison: Classify examples and distinguish types.
  4. Actual event sequence: Trace the original form.
  5. Usability and safe output: Explain and test the design.
  6. Evidence and transfer: Submit and improve an accurate artefact.


Worked checks and assessment guidance

  1. HTML defines the labelled input, form, buttons and result element; CSS provides spacing, sizing and other presentation; JavaScript registers events and performs decisions. The DOM is the document interface. const prevents reassignment of its binding, not all object-property changes, so DOM elements can still receive properties. let is appropriate for the numerical counter that changes after valid checks.
  2. The function accepts decimal digits with an optional sign and surrounding whitespace, within minus one thousand through one thousand inclusive. It rejects empty or whitespace-only text before Number can turn it into zero. Decimal-point, exponent and hexadecimal spellings are outside the announced grammar. Integer and range checks follow conversion; strict equality does not replace them. Failed results provide a message rather than an invented valid zero.
  3. Fourteen has remainder zero on division by two and is Even; nine and negative three have nonzero remainders and are Odd. Zero and accepted negative-zero spelling are Even. Numerical fourteen is not strictly equal to text fourteen, whereas loose equality can convert types for comparison. The Python branch uses double equals for equality and indentation; the JavaScript branch deliberately uses triple equals and braces.
  4. Button or Enter submission invokes one registered form handler. It prevents default navigation, reads input.value, calls the pure classifier and either displays an error or updates the result and increments the local valid-check count. Editing the input marks the old result stale. Clear empties the field, resets the count and restores input focus. The count is neither a correctness percentage nor a platform learning-point award.
  5. The associated label and helper text clarify accepted input; native buttons support keyboard activation and explicit words avoid colour-only meaning. The result uses textContent, a status role and polite live-region setting. Actual announcements still depend on browser and assistive technology, so these choices do not certify universal accessibility. A narrow layout and forty-four-pixel controls should be verified with real interaction and layout checks, not inferred only from CSS source.
  6. Provide runnable complete JavaScript, independent expected values, actual pure-function results and button/keyboard tests including empty, malformed, valid, boundary and changed-input cases. Update interface labels and tests when changing the range. An approved fresh preview is distinct from inserting code into unrelated sites. Known-user observations must be real and minimally recorded; an author simulation is not a real user study or completion of the wider multi-application curriculum requirement.


Learning evidence

Submit the complete original or equivalent JavaScript interaction, a clear description of HTML/CSS/JavaScript roles, a labelled input and working event handler. Include independent expected-versus-actual pure-function and real event tests, keyboard and narrow-layout observations, invalid and boundary cases, and an honest distinction between author simulation and actual known-user feedback. No real account or personal learner data is needed.


OER and Wikipedia

Original decimal-input contract, classification function, complete DOM interface, traces and exercises. MDN Number reference, strict equality and addEventListener support language and browser semantics; the concrete form and tests are independently authored. DfE Computing programme of study, KS3 textual programming and creative projects. Year 8 sequencing is editorial and these are contributions to broader requirements, not claims of complete curriculum certification. Primary references checked 14 November 2026 local time. Original videos identify Programming with Mosh and Corey Schafer; optional video advertising claims are not course guarantees. Unchanged Commons logos explain technology roles, with exact authors and licences retained and no endorsement implied.

HTML5 logo and wordmark.svg, W3C, CC BY 3.0. Unchanged original; caption and learning activities are original.

CSS3 logo and wordmark.svg, Rudloff, CC BY 3.0. Unchanged original; caption and learning activities are original.


Linked learning areas


aiMOOC Projects



Schulfach+




aiMOOCs



aiMOOC Projekte









MOOCwiki · Deutsch

Nach dem Lernen ist vor dem Lernen

Entdecke direkt den nächsten Lernkurs. Weitere Inhalte erscheinen, wenn Du weiter nach unten scrollst.

Zur MOOCwiki-Hauptseite

Mediathek

Suche verfeinern

Dein Lernplan bestimmt, was oben steht. Alle anderen Inhalte bleiben erreichbar. Seitenaufrufe beeinflussen die Auswahl nicht.

Inhalte werden geladen ...

Mediathek wird aus dem Wiki geladen ...