Computer Programming 1 (JavaScript) • Web Basics (DOM & Events)

Updating UI Based on State — I can update the UI based on program state (show results, clear fields) at my level.

Learn how JavaScript programs track data in variables and use that data to change what users see on screen.

A JavaScript data file with code brackets and a laptop.
Inside this lesson 10 sections 5 questions 4 figures

SECTION 1

Historical Context & Motivation

In the early days of the web, pages were completely static. A server sent an HTML file to your browser, the browser displayed it, and that was it — nothing changed unless you clicked a link to load an entirely new page. If you wanted to show a user their quiz score, the page had to reload from scratch. This was slow, clunky, and nothing like the interactive apps we use today.

The idea of updating the UI based on state — changing what users see on screen by modifying data stored in your program — is the core pattern behind every modern web application. From Instagram feeds refreshing with new posts, to a Google Form clearing after you submit it, to a shopping cart updating its total, all of these experiences rely on the same fundamental concept: your code keeps track of data (the state), and when that data changes, the code updates the visible page (the UI, or User Interface) to match.

1995 • JavaScript Is Born

Brendan Eich creates JavaScript in just 10 days at Netscape. For the first time, browsers can run code that reacts to user actions without reloading the page.

1998 • The DOM Standard Emerges

The W3C publishes the Document Object Model (DOM) specification, giving JavaScript a standardized way to read and modify any element on a web page.

2005 • AJAX & Web 2.0

Gmail and Google Maps popularize asynchronous page updates. Users begin expecting pages that update instantly without full reloads — state-driven UI becomes essential.

2013–2015 • React & Modern Frameworks

Facebook releases React, which formalizes the idea that the UI is a direct function of state. The same pattern you will learn in this lesson is the foundation of these professional tools.

The central question this lesson answers is straightforward: How do I use JavaScript to change what appears on a web page based on data my program is tracking? By the end, you will be able to show results to users, clear input fields, and toggle visibility — all by writing code that connects state to the DOM.

SECTION 2

Core Principles & Definitions

Before writing any code, you need to understand a few key ideas that make state-driven UI possible. These principles are not unique to JavaScript — they apply to nearly every programming environment that builds user interfaces.

1

State

The data your program keeps track of at any given moment. State lives in variables (e.g., a score, a username, or whether a form has been submitted). When state changes, the UI should change too.
2

UI (User Interface)

Everything the user sees and interacts with on the page — text, buttons, images, input fields. In web development, the UI is built from HTML elements styled with CSS.
3

DOM (Document Object Model)

The browser's live representation of your HTML. JavaScript can access and modify DOM elements using methods like document.getElementById(). Changing the DOM is how you change the UI.
4

Event → State → UI Cycle

The standard flow: a user action (event) triggers code that updates state (variables), then additional code reads the new state and updates the DOM (UI). This cycle repeats for every interaction.
5

Rendering

The process of writing state values into the DOM so the user can see them. This might mean setting element.textContent, toggling a CSS class, or clearing an input's value property.
✦

KEY TAKEAWAY

Think of state like a scoreboard at a basketball game. The actual score (state) is tracked behind the scenes by the scorekeeper. The big display board (UI) only shows what the scorekeeper tells it to show. When someone scores a basket, the scorekeeper updates the number first, and then the board refreshes. Your JavaScript variables are the scorekeeper, and the DOM is the display board.

SECTION 3

Visual Explanation — The State-to-UI Flow

The diagram below illustrates the complete cycle that happens every time a user interacts with your page. Follow the arrows from left to right to see how a button click travels through your code and ultimately changes what appears on screen.

Event → State → UI Cycle1. USER EVENTUser clicks a button,types in a field, orsubmits a form.2. UPDATE STATEEvent handler runs.JavaScript variablesare updated.3. RENDER UICode reads new stateand writes it intothe DOM elements.User sees updated UI and interacts again…button.addEventListener("click", handleClick)score = score + 10;message = "Great!";el.textContent = score;input.value = "";
The three boxes across the top show the high-level flow: a user event triggers code that updates state, which is then rendered into the UI. The code snippets at the bottom show actual JavaScript for each stage. The dashed arrow loops back because the user can interact again, restarting the cycle.

Notice how the code snippets at the bottom correspond to each stage. The event listener sets up the connection between the user and your code. The state update happens inside the handler function. And the rendering step is where you push the new values into the page. This three-step pattern is remarkably consistent — whether you are building a simple counter or a complex dashboard, the cycle remains the same.

SECTION 4

How It Works — DOM Methods for Updating UI

Now let's look at the specific JavaScript tools you will use most often to read state and push it into the DOM. These are not abstract concepts — they are actual methods and properties built into every web browser.

Selecting Elements

Before you can change an element, you need a reference to it. The two most common selection methods are document.getElementById("myId") and document.querySelector(".myClass"). The first finds an element by its unique id attribute; the second uses any CSS selector. Both return a DOM element object that you can store in a variable and manipulate later.

Changing Text Content

The textContent property lets you read or overwrite the text inside an element. For example, resultEl.textContent = "You scored " + score + " points!"; takes the current value of the score variable and writes a message into the element. This is the most direct way to show results to the user.

Clearing Input Fields

Input elements have a value property that corresponds to whatever the user has typed. To clear a field after the user submits, you simply set inputEl.value = "";. This resets the field to blank, giving the user a clear signal that their input was received and the form is ready for the next entry.

Showing and Hiding Elements

You can control visibility using the classList property. If you define a CSS class like .hidden { display: none; }, you can add or remove it in JavaScript: element.classList.add("hidden") hides the element, and element.classList.remove("hidden") reveals it. The method element.classList.toggle("hidden") flips between the two states automatically.

Changing Styles Directly

For quick visual feedback, you can modify inline styles via element.style.color = "green" or element.style.backgroundColor = "#fef3c7". While toggling CSS classes is generally preferred for maintainability, direct style changes work well for small, one-off updates like highlighting a correct answer.

⚠

Common Pitfall

Don't confuse textContent and value. Use textContent for display elements like <p>, <span>, and <h1>. Use value for form elements like <input> and <textarea>. Mixing them up is one of the most frequent beginner bugs.

SECTION 5

Common UI Update Patterns

Now that you know the individual DOM methods, let's see how they combine into recognizable patterns. The diagram below shows four common scenarios you will encounter in nearly every beginner JavaScript project. Each pattern follows the same Event → State → UI cycle but applies different DOM methods.

Four Common UI Update PatternsPattern A: Show a Result// Statelet total = price * quantity;// RenderresultEl.textContent ="Total: $" + total;Total: $49.99Pattern B: Clear a Field// Read state from inputlet name = inputEl.value;// Clear the fieldinputEl.value = "";field is now emptyPattern C: Show / Hide an Element// Statelet isVisible = true;// Toggle renderif (isVisible) {box.classList.remove("hidden");} else {box.classList.add("hidden");}Pattern D: Update Style Based on State// Statelet isCorrect = checkAnswer();// Renderif (isCorrect) {box.style.borderColor = "green";msg.textContent = "Correct!";} else {box.style.borderColor = "red";}
Each panel demonstrates a different UI update pattern. Pattern A writes computed results to the page. Pattern B clears an input after capturing its value. Pattern C toggles element visibility with a CSS class. Pattern D applies conditional styling based on a boolean state variable.

These four patterns cover the vast majority of what you will do in a beginner JavaScript project. Pattern A and Pattern B are by far the most common — showing a calculated result and resetting the form for the next use. Patterns C and D add polish by controlling what the user sees and how it looks. In practice, you will often combine two or three patterns in a single event handler.

SECTION 6

Worked Example — A Tip Calculator

Let's walk through building a simple tip calculator step by step. The user enters a bill amount and clicks a button. The program calculates a 20% tip, displays the result, and clears the input field. This example combines Patterns A and B from the previous section.

Tip Calculator — Full Walkthrough

  1. 1

    Step 1 — Write the HTML Structure

    Start with the HTML that defines the user interface. You need an <input> for the bill amount, a <button> to trigger the calculation, and a <p> to display the result. Each element needs an id so JavaScript can find it.
    <input id="billInput" type="number" placeholder="Enter bill"> · <button id="calcBtn">Calculate Tip</button> · <p id="result"></p>
  2. 2

    Step 2 — Select DOM Elements in JavaScript

    Use document.getElementById() to grab references to each element and store them in variables. Do this once at the top of your script so the references are ready before any events fire.
    const billInput = document.getElementById("billInput"); const calcBtn = document.getElementById("calcBtn"); const resultEl = document.getElementById("result");
  3. 3

    Step 3 — Attach an Event Listener

    Add a click event listener to the button. The callback function will contain all of the logic for updating state and rendering the UI. This is the bridge between the user's action and your code.
    calcBtn.addEventListener("click", function() { ... });
  4. 4

    Step 4 — Read State and Compute the Tip

    Inside the callback, read the bill amount from the input's value property. Since value is always a string, convert it to a number with Number() or parseFloat(). Then compute the tip by multiplying by 0.20. These variables represent your program's state.
    let bill = Number(billInput.value); let tip = bill * 0.20;
  5. 5

    Step 5 — Render the Result and Clear the Field

    Write the tip amount into the result paragraph using textContent. Use toFixed(2) to format the number to two decimal places. Then clear the input field by setting its value to an empty string. The UI now reflects the computed state, and the form is ready for another calculation.
    resultEl.textContent = "Tip: $" + tip.toFixed(2); billInput.value = "";
💡

Try It Yourself

Open your browser's Developer Tools (press F12), go to the Console tab, and type document.title to see the DOM in action. Then try changing it: document.title = "My Page". You just updated the UI based on state!

SECTION 7

Comparing UI Update Approaches

There are multiple ways to update the DOM in JavaScript. The table below compares four approaches you might encounter. As a beginner, you should focus on the first two methods (highlighted in green) because they are the safest and easiest to understand.

MethodBest ForProsCons
textContentDisplaying plain text resultsSafe, fast, and simple. No risk of injecting unwanted HTML.Cannot render HTML tags — only plain text.
classListShowing, hiding, or styling elementsKeeps style logic in CSS where it belongs. Easy to toggle.Requires a predefined CSS class.
innerHTMLInserting formatted HTMLCan create new elements with tags like <strong>.Security risk (XSS) if used with user input. Avoid for now.
element.styleQuick one-off style changesDirect and immediate. Good for dynamic values like color.Mixes styling into JavaScript. Hard to maintain at scale.

Comparison of common DOM update methods

✦

KEY TAKEAWAY

Think of these methods like different tools in a toolbox. textContent is your screwdriver — you'll use it constantly because most UI updates are just changing text. classList is your wrench — great for toggling predefined states. innerHTML is a power tool — powerful but dangerous if misused. Start with the basics, and reach for advanced tools only when simpler ones won't do the job.

SECTION 8

Connection to Advanced Concepts

The pattern you learned in this lesson — manually reading state, then manually updating the DOM — is exactly how vanilla JavaScript works. But as applications grow larger, managing these updates by hand becomes tedious and error-prone. That is why developers created frameworks and libraries that automate the rendering step. Understanding the manual version first is essential because every framework is built on top of these same DOM methods.

ConceptWhat You Learned (Vanilla JS)Advanced Version
Storing stateRegular variables (let score = 0)State management (React useState, Vuex, Redux)
Rendering UIManually setting textContent / classListDeclarative templates that auto-update when state changes
Handling eventsaddEventListenerFramework event bindings (onClick in React, @click in Vue)
Keeping UI in syncYou must remember to update every elementFrameworks use a virtual DOM or reactive system to sync automatically

Vanilla JavaScript vs. Modern Frameworks

The right column in the table above might look complex, but every single concept builds directly on what you practiced today. When you learn React, Vue, or another framework later, you will recognize the Event → State → UI cycle immediately. The framework just handles the "render" step for you, while you focus on defining state and writing logic.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

In the Event → State → UI cycle, explain in your own words why you should update the state variable before you update the DOM. What could go wrong if you skip the state update and write directly to the DOM?
Show answer
You should update state first because the state variable is your program's single source of truth. If you write directly to the DOM without updating the variable, then other parts of your code that reference that variable will have outdated information. For example, if you display a score on screen but never update the score variable, a later calculation that uses score (like computing a grade) will use the wrong number. Keeping state and UI in sync prevents these kinds of subtle bugs.

Question 2: BASIC CALCULATION

You have an <input id="tempInput"> where the user types a temperature in Fahrenheit, and a <p id="celsiusResult"></p> to display the Celsius conversion. Write the JavaScript code inside a button's click handler that reads the input, converts to Celsius using the formula C = (F − 32) × 5 ÷ 9, displays the result, and clears the input.
Show answer
Inside your click handler, you would write: let fahrenheit = Number(document.getElementById("tempInput").value); to read the input and convert to a number. Then let celsius = (fahrenheit - 32) * 5 / 9; to compute the state. Then document.getElementById("celsiusResult").textContent = celsius.toFixed(1) + "°C"; to render the result. Finally, document.getElementById("tempInput").value = ""; clears the input. This follows the full Event → State → UI pattern.

Question 3: INTERMEDIATE

You are building a to-do list. You have a variable let tasks = []; and an input field. When the user clicks "Add Task," the task should be added to the array, the full list should appear inside a <ul id="taskList">, and the input should clear. Write the event handler. (Hint: you can set textContent on the <ul> or use a loop to build the list string.)
Show answer
First, read the input: let newTask = taskInput.value;. Then update state: tasks.push(newTask);. To render, you can build a string with a loop: let html = ""; for (let i = 0; i < tasks.length; i++) { html += "<li>" + tasks[i] + "</li>"; } and then set taskList.innerHTML = html;. (Using innerHTML here is acceptable because the content comes from the user's own input within a controlled local environment.) Finally, clear the input: taskInput.value = "";. The key insight is that you re-render the entire list from the array each time, ensuring the UI always matches the state.

Question 4: APPLIED

A quiz app has a variable let score = 0; and a <span id="scoreDisplay">0</span>. Each question has four answer buttons. When the user clicks the correct answer, the score should increase by 10, the display should update, and the correct button should turn green while incorrect buttons turn red. Describe the state variables you would need and the DOM updates for each.
Show answer
You would need at least two state variables: let score = 0; to track points, and a variable or data attribute storing which answer is correct (e.g., let correctAnswer = "B";). Inside the click handler for each button, compare the clicked answer to correctAnswer. If it matches, run score += 10; and scoreDisplay.textContent = score;. Then use clickedButton.style.backgroundColor = "green"; for the correct button and loop through the other buttons to set them red. This combines Pattern A (show result), Pattern D (conditional styling), and state tracking across multiple interactions.

Question 5: CRITICAL THINKING

Consider a web page with five different sections that all display the same username variable (a header greeting, a profile card, a sidebar, etc.). If the user changes their name, you must update all five places. What problems could arise if you forget to update one of them? Propose a strategy using a single "render" function that keeps every part of the UI in sync with state.
Show answer
If you forget to update even one display location, the UI becomes inconsistent — the header might say "Alex" while the sidebar still says "Guest." This confuses users and suggests buggy software. A better approach is to create a single function like function renderUsername() { } that reads the username variable and updates all five DOM elements at once. Whenever the username state changes, you call renderUsername() instead of manually updating each element. This centralizes rendering logic in one place, making it impossible to forget an element. This is essentially the pattern that modern frameworks like React automate — they call a render function every time state changes, ensuring the entire UI stays in sync.

SUMMARY

Lesson Summary

Summary

In this lesson, you learned the fundamental pattern behind every interactive web page: the Event → State → UI cycle. A user event (like a button click) triggers your JavaScript code, which updates state stored in variables. Your code then renders the new state into the DOM using properties like textContent and value, and methods like classList.add() and classList.remove().

You practiced four key patterns: showing results by writing computed values to the page, clearing input fields by resetting value to an empty string, showing and hiding elements with CSS classes, and conditionally styling elements based on boolean state. These same principles scale up to power every modern web framework, making this one of the most important skills in all of front-end development.

Varsity Tutors • Computer Programming 1 (JavaScript) • Updating UI Based on State