Skip to main content

Featured

Space Explorers Book 7: Answers and Explanations

Memunic Space Explorers › Book 7: Memoon and the Search for Another Home › Answers and Explanations Answers and Explanations Habitable means life could live there; inhabited means life does live there. A world can be habitable and empty, as an unoccupied flat has a roof and water but nobody in it. The Moon has almost no air, so water would boil or freeze, and its gravity is only about one-sixth of Earth’s, too weak to keep air. Accept also: no greenhouse blanket, so it swings between very hot and very cold. Venus. It matches Earth in size and roughly in mass, but its thick carbon dioxide air traps heat, making it hot and crushing. “Twin” is only true for size and weight. A dip of 1 per cent means (planet width divided by star width) squared is 0.01, so the ratio is 0.1: the planet is about a tenth as wide as the star. Repeats at the same gap show the planet is going round the star in 12 days, and rule out a one-time event such as a passing object. A planet shines only by reflected l...

Byte by Byte Book 8: Chapter 4 – The DOM and Events: Making Web Pages Interactive

Byte by Byte › Book 8: Real-World Coding, Data and AI › Chapter 4: The DOM and Events: Making Web Pages Interactive

Chapter 4: The DOM and Events: Making Web Pages Interactive

Illustration from Byte by Byte Book 8: Chapter 4 – The DOM and Events: Making Web Pages Interactive

🔎 The Case

Simbha's code works, but visitors cannot open a browser console. The booking logic must connect to the page itself: a box to type tickets into, a button to press, and a message that appears on screen. Beautine, Keeper of Records, looks at the HTML and says, "It's a family tree." She is right, and that tree has a name.

💡 The Concepts

The DOM (Document Object Model). When a browser loads HTML, it builds a tree of objects in memory, one node per element. document is the root. JavaScript reads and changes this tree, and the browser redraws the page instantly. HTML is the starting state; the DOM is the live page.

Selecting elements.

  • document.getElementById("total") finds the element with id="total" .
  • document.querySelector(".stand") finds the first match for any CSS selector; querySelectorAll finds all matches.

Changing elements.

  • el.textContent = "Booked!" sets the text.
  • el.style.color = "red" changes one style; better, el.classList.add("full") applies a CSS class.
  • input.value reads what the user typed (always a string).
  • document.createElement("li") plus list.appendChild(item) adds new elements.

Events. An event is something that happens: a click, a key press, a form submit, the page finishing loading. An event listener is a function that runs when the event happens:

button.addEventListener("click", handleBooking);

This is event-driven programming: the program sets up listeners, then waits. Common events: click , input , change , submit , keydown , mouseover .

Forms. When a form submits, the browser reloads the page by default. Call event.preventDefault() inside the handler to stop that.

Saving data in the browser. localStorage.setItem("seats", "120") and localStorage.getItem("seats") keep small text values between visits on that one browser. Never store passwords or personal data there.

Security note. Never put text typed by users into the page with innerHTML ; a user could inject a script (this attack is called cross-site scripting, XSS). Use textContent .

🛠️ Build It

Replace the <body> of index.html :

<body>
  <h1>Memunic Games Booking</h1>
  <form id="bookForm">
    <label>Stand
      <select id="stand">
        <option>North</option><option>South</option>
        <option>East</option><option>West</option>
      </select>
    </label>
    <label>Tickets <input id="tickets" type="number" min="1" value="1"></label>
    <button type="submit">Book</button>
  </form>
  <p id="message"></p>
  <ul id="standList"></ul>
  <script src="app.js"></script>
</body>

Keep allStands , bookingCost and book from Chapter 3 (delete the console.log lines) and add:

const form = document.getElementById("bookForm");
const message = document.getElementById("message");
const list = document.getElementById("standList");
function showStands() {
  list.textContent = "";
  for (const s of allStands) {
    const li = document.createElement("li");
    li.textContent = `${s.name}: ${s.seats > 0 ? s.seats + " seats left" : 
"FULL"}`;
    if (s.seats === 0) li.classList.add("full");
    list.appendChild(li);
  }
}
form.addEventListener("submit", function (event) {
  event.preventDefault();
  const standName = document.getElementById("stand").value;
  const tickets = Number(document.getElementById("tickets").value);
  message.textContent = book(standName, tickets);
  showStands();
});
showStands();

Add <style>.full { color: crimson; text-decoration: line-through; }</ style> in the <head> . Book tickets until a stand turns red.

✅ Case Closed

The booking desk is now a real web app: the page reacts to the user, validates input and updates itself without reloading. On Games morning the queue moves in minutes. Pip asks, "What happens if I refresh?" The seats reset. Memoon notes this honestly as a limitation: real systems store bookings on a server in a database, so everyone sees the same numbers. That is what back-end developers build; what you built is the front end.

❓ Test Yourself

  1. What is the DOM, and how is it different from the HTML file?
  2. Write the code to change the text of <h2 id="title"> to "Results".
  3. What does addEventListener do? Name four events.
  4. Why do we call event.preventDefault() on a form?
  5. Why is textContent safer than innerHTML for user input?
  6. Challenge: Add a "Reset" button that sets every stand back to its starting seats and redraws the list.

📚 Key Terms

DOM · node · document · getElementById · querySelector · textContent · classList · value

  • createElement · appendChild · event · event listener · event-driven programming ·

preventDefault · localStorage · cross-site scripting (XSS) · front end · back end · server

Keep learning with Byte by Byte

Explore Book 8: Real-World Coding, Data and AI. Find the ebook, purchase details and teaching slides on MemuniCity.

Watch this chapter on YouTube

Comments

Popular posts from this blog

CA-7 Job Status and Failure Reason Codes

Here are the various status codes that You may see for jobs in the Queue or Logs in CA-7. R-C0002 R-C0003 R-C0099 R-C0255 R-JCLER A-U0002 A-U0004 A-U0015 A-U0043 A-U4095 A-SOC7 A-U4000 Reason Code/Job Status Code explanation: The indication of the job's current disposition. Values and their meanings are: A-Snnnn-- The job has failed with a system abend. A-Unnnn --The job has failed with a user abend. C-Cnnnn --The job has completed successfully and is going through completion processing. E-ARFATT-- An error occurred during the attempt to attach ARF definitions. This can result if the ARFSET specified is not defined. A diagnostic message may have been written to the CA-7 log, the OS console, or to the trailer queue for the job (in which case it can be displayed using LQ,JOB=x,LIST=ALL). E-ARFERR ---The job encountered an error in the ARF processing. Do a LARFQ command for the job to get more specific information. E-SEGERR --The job has been requeued...

Whistling Winds and Waterfalls: 4 Days of Magic in Shillong

Nestled in the clouds, where the scent of pine trees mingles with the rhythm of waterfalls and the tunes of local guitar-strumming youth—Shillong is more than a place. It’s a vibe. If you’ve got 3 nights and 4 days, you’ve got just enough time to fall in love. Here’s how to make the most of it—food, fun, fog and fantastic views included. Day 1: Shillong, We’re Coming for You! You land in Guwahati, barely out of the airport when the hills start calling. You hop into your cab, Spotify on, windows down, and the three-hour ride to Shillong begins. Just when you think it can’t get better, you stop at Umiam Lake —a lake so calm, it looks like someone ironed the water. By evening, you’re sipping hot chai in Laitumkhrah, maybe nibbling on spicy momos or pork jadoh from a roadside stall. You’re checked into your charming hotel ( Tripura Castle if you fancy old-world royalty, Ri Kynjai if you’re into lakeside poetry). The breeze whispers secrets of waterfalls and pine forests. Sleep well, drea...

Installing and Configuring Hadoop on Ubuntu as a Pseudo Distributed Single Node Cluster

Briefly what is psuedo-distributed single node Hadoop cluster: It is a Hadoop distributed cluster having Single Node. All the five daemons (NN,DN,JT,TT,SNN) are running as individual JVM (java process) instances. We will get all distributed features of Hadoop. This mode is used to develop, test, and staging (before production) Map Reduce programs quickly. It writes all the system, daemon and user logs to different files on the cluster To install Hadoop in this mode, we have to modify the hadoop-env.sh, core-site.xml, hdfs-site.xml, mapred-site.xml. hadoop-env.sh contains all the Environment variables which are required for running Hadoop. All the default values are fine, Only we have to modify the JAVA_HOME=“The location of Java Home Directory” Core-site.xml contains all the cluster specific information like io, temp directory, sorting, file system uri etc. Hdfs-site.xml contains all the parameters which are specific to HDFS like name node directory, data node directory...