Skip to main content
March 23, 2026Dan Rodney/8 min read

Dynamically Changing Content with Custom Objects

Master Dynamic Content Updates with JavaScript Objects

Core JavaScript Concepts in This Tutorial

DOM Manipulation

Learn to reference and modify HTML elements dynamically using JavaScript's document object model methods.

Event Handling

Implement change event listeners to respond to user interactions without page reloads.

Data Integration

Load and access external JavaScript objects to populate content dynamically based on user selections.

Topics Covered in This JavaScript Tutorial:

Referencing DOM elements, implementing event listeners for user interactions, loading external data sources, and dynamically updating page content without page refreshes—essential skills for modern interactive web development.

Exercise Preview

preview custom objects

Exercise Overview

In this hands-on exercise, you'll master the art of creating dynamic, single-page applications using JavaScript objects. You'll build a responsive interface where user selections instantly update content without page reloads—a fundamental technique in modern web development that enhances user experience and reduces server load. This approach mirrors the interactive patterns you'll find in professional web applications, from e-commerce product filters to dashboard interfaces.

Single Page Application Concept

This exercise demonstrates the foundation of single-page applications where content updates without page reloads, improving user experience and performance.

Getting Started

Before diving into the code, let's set up your development environment and familiarize ourselves with the project structure.

  1. Navigate to the State-Facts folder located in Desktop > Class Files > JavaScript Class. Open this entire folder in your code editor (Visual Studio Code, WebStorm, or similar) to access the complete project structure.
  2. In your code editor, open index.html from the State-Facts folder. Take a moment to scan the HTML structure—you'll notice placeholder content that we'll dynamically populate.
  3. Preview index.html in Chrome. We'll leverage Chrome DevTools throughout this exercise for debugging and testing.

    Currently, the Choose a State dropdown menu is static. Our goal is to transform this into an interactive element that instantly displays relevant state information when users make a selection—no page refreshes required. This seamless interaction pattern is what users expect from modern web applications.

  4. Keep the page open in Chrome—we'll return to it frequently to test our progressive enhancements.

Setup Requirements

0/3

Referencing the Menu

The foundation of any interactive element is establishing a reliable reference to it in the DOM. Let's create that connection and understand how form elements expose their data.

  1. Return to index.html in your code editor and examine the code structure.
  2. Locate the select tag on line 17, which defines our dropdown menu.

    • Notice each option element contains a value attribute with a state abbreviation—this standardized format will serve as our data key.
    • This value becomes our lookup mechanism: when users select a state, we'll capture this value and use it to retrieve the corresponding state data from our data source.
  3. Just before the closing </body> tag, add the following code to establish a reference to the select element:

    </div>
       <script>
          let stateList = document.getElementById('state-list');
       </script>
    </body>
  4. Let's examine this element in detail by logging it to the Console. Add the following code:

    let stateList = document.getElementById('state-list');
    console.log(stateList);
  5. Save the file and reload the page in Chrome.
  6. Open the Console using Cmd–Opt–J (Mac) or Ctrl–Shift–J (Windows).

    • The Console displays the complete select element with all its HTML structure.
    • Click the arrow to expand the element and explore the nested option elements—this shows you the full DOM structure you're working with.

    While seeing the HTML is useful, we need access to the element's properties and methods for programming purposes.

  7. Replace log with dir to see the element's JavaScript properties:

    console.dir(stateList);
  8. Save and reload the page in Chrome.

    • Now the Console shows select#state-list—a JavaScript object representation.
    • Expand this object and scroll past the options list to find the extensive collection of properties and methods available.
    • Locate the value property, currently set to "usa". When users select different states, this value automatically updates to the chosen state's abbreviation (like "ny" or "ca"). This dynamic value property is our key to responsive interactivity.

    Pro tip: Clear the Console anytime using Cmd–K (Mac) or Ctrl–L (Windows) to maintain a clean debugging environment.

  9. Let's isolate the value property by appending .value:

    console.dir(stateList.value);
  10. Save and reload the page in Chrome.

    The Console now displays usa—the current default value. Once we implement our event listener, this will dynamically reflect user selections.

Console Methods: log vs dir

Featureconsole.logconsole.dir
Output FormatHTML representationObject properties
Best Use CaseView DOM structureInspect object properties
Debugging ValueVisual HTML layoutProperty exploration
Recommended: Use console.dir when you need to explore object properties and methods
Developer Console Shortcuts

Clear Console: Cmd+K (Mac) or Ctrl+L (Windows). Open Console: Cmd+Opt+J (Mac) or Ctrl+Shift+J (Windows).

Listening for When the Menu is Changed & Getting the Chosen Value

Event listeners are the backbone of interactive web applications. While you've likely worked with click and mouseover events, the 'change' event is specifically designed for form elements and provides the perfect trigger for our dropdown functionality.

  1. Event listeners require a callback function to execute when triggered. Let's wrap our console output in a function:

    let stateList = document.getElementById('state-list');
    function showStateInfo() {
       console.dir(stateList.value);
    };
  2. Now attach an event listener that triggers our function when the menu changes:

    let stateList = document.getElementById('state-list');
    function showStateInfo() {
       console.dir(stateList.value);
    };
    stateList.addEventListener('change', showStateInfo);
  3. Here's a JavaScript best practice: the this keyword provides context-aware references. In event handler functions, this refers to the element that triggered the event, making your code more flexible and reusable. Update the reference:

    function showStateInfo() {
       console.dir(this.value);
    };
  4. Save and reload the page in Chrome to test the interactive functionality.

    • Select any state from the dropdown menu.
    • The Console immediately displays the selected state's abbreviation—proof that our event listener is working correctly.
    • Try several different states to confirm consistent behavior.

    Excellent! With our event detection working reliably, we can now focus on the core functionality: retrieving and displaying state-specific information.

Event Listener Implementation

1

Create Handler Function

Wrap your logic in a named function that can be called when the event triggers

2

Add Event Listener

Use addEventListener with 'change' event to detect menu selections

3

Use 'this' Context

Replace direct element reference with 'this' to reference the calling object

Loading in the State Data from an External File

Professional web applications separate data from presentation logic. We've prepared a comprehensive state data object that demonstrates this architectural principle while providing rich information for our interface.

  1. In your code editor, navigate to the js folder and open state-data.js.

    This file contains a carefully structured JavaScript object named stateData. Notice the opening curly brace on line 1—this indicates an object literal containing nested objects for each state. Each state object includes comprehensive properties: name, abbreviation, capital, population, and other relevant data. This hierarchical structure (objects within objects) is a common pattern in JSON APIs and modern web development.

  2. To access this data object, we need to include it in our HTML page. Switch back to index.html.

  3. Above your existing script tag, add a link to the external JavaScript file:

    </div>
    <script src="js/state-data.js"></script>
    <script>
  4. Let's test access to the state data by adding this line after your event listener:

    stateList.addEventListener('change', showStateInfo);
       console.log(stateData.ny.name);
    </script>
  5. Save and reload the page in Chrome.

    The Console should display New York, confirming successful access to our data structure.

  6. Return to your code editor to explore alternative syntax.
  7. JavaScript offers two ways to access object properties. Replace the dot notation with bracket notation:

    console.log(stateData['ny'].name);
  8. Save and reload the page in Chrome.

    You'll see New York again, demonstrating that both syntaxes work identically.

    The bracket syntax becomes essential when working with dynamic property names—variables that change at runtime. Since our state abbreviations come from user selections (variables), we'll need this bracket approach throughout our application.

Object Property Access Methods

Two ways to access object properties: dot notation (object.property) and bracket notation (object['property']). Bracket notation is required for dynamic property names.

State Data Object Structure

Parent Object

stateData contains all state information as a master object with state abbreviations as keys.

Child Objects

Each state has properties like name, abbreviation, capitol, and other state-specific information.

Dynamically Changing Info on the Page

Now we'll implement the core feature: real-time content updates based on user selections. This technique forms the foundation of responsive, single-page applications that feel fast and intuitive.

  1. In your HTML around line 76, locate the info-name figcaption element. This will display the selected state's full name.

  2. Modify the showStateInfo function to capture the selected value:

    function showStateInfo() {
       let selectedState = this.value;
    };
  3. Move our test console.log into the function where it can access the selected state:

    function showStateInfo() {
       let selectedState = this.value;
       console.log(stateData['ny'].name);
    };
  4. Replace the console output with actual DOM manipulation:

    function showStateInfo() {
       let selectedState = this.value;
       document.getElementById('info-name').innerHTML = stateData['ny'].name;
    };
  5. Now make it truly dynamic by using the selected state instead of the hardcoded 'ny':

    document.getElementById('info-name').innerHTML = stateData[selectedState].name;

    Important: Notice we must use bracket notation here. The dot syntax stateData.selectedState would look for a literal property named "selectedState" rather than evaluating the variable's value. Bracket notation evaluates the variable and uses its value as the property key.

  6. Save and reload the page in Chrome.

    • Select any state from the dropdown menu.
    • Watch as the state name below the image updates instantly—you've just implemented dynamic content rendering!
    • Test multiple states to confirm consistent behavior across all options.

Dynamic Content Update Process

1

Capture Selection

Store the selected value from the menu in a variable for reuse

2

Reference Target Element

Use getElementById to target the specific element that needs updating

3

Update Content

Set innerHTML property using data from the external object based on selection

Dynamically Changing the Rest of the Page Info

With the pattern established, let's implement updates for all remaining page elements to create a fully interactive state information display.

  1. Return to your code editor to expand the functionality.
  2. Copy this line to use as a template for additional updates:

    document.getElementById('info-name').innerHTML = stateData[selectedState].name;
  3. Paste a copy immediately below the original.
  4. Update the copy to handle state abbreviation display:

    document.getElementById('info-name').innerHTML = stateData[selectedState].name;
    document.getElementById('info-abbr').innerHTML = stateData[selectedState].abbr;

    Note: Each state object in state-data.js includes an abbr property containing the official state abbreviation.

  5. Save and reload the page in Chrome to test the expansion.

    • Select a state from the dropdown.
    • Both the state name and abbreviation should update simultaneously, demonstrating coordinated content updates.
  6. Return to your code editor for the final implementation phase.
  7. Rather than having you manually type each property update, we've prepared the complete code. In the snippets folder, open change-function-code.js.

  8. Copy all the provided code.
  9. Switch back to index.html and paste the new code below your existing two document.getElementById lines.
  10. Save and reload the page in Chrome for comprehensive testing.

    Select any state—you should see all textual information update instantly: name, abbreviation, capital, population, and other details. This demonstrates the power of coordinated DOM updates driven by a single user action.

  11. Let's complete the experience by implementing dynamic image updates. First, examine the img folder in your code editor's sidebar.

    Notice the strategic naming convention: each image filename matches its corresponding state abbreviation. This consistency enables programmatic image selection without complex mapping logic.

  12. Add the image update functionality to your showStateInfo function:

    let selectedState = this.value;
    document.getElementById('info-pic').src = 'img/' + selectedState + '.jpg';
    document.getElementById('info-name').innerHTML = stateData[selectedState].name;
  13. Save and reload the page in Chrome for the final test.

    Select any state from the dropdown—the image, name, and all associated information should update simultaneously, creating a seamless, professional user experience that rivals modern web applications.

File Naming Convention Benefits

Images are named to match state abbreviations, enabling dynamic image loading using string concatenation with the selected state value.

Complete Implementation Checklist

0/4

Key Takeaways

1JavaScript objects enable dynamic content updates without page reloads, forming the foundation of modern single-page applications
2Event listeners with 'change' events can capture user menu selections and trigger content updates in real-time
3The 'this' keyword in event handler functions refers to the element that triggered the event, providing clean code organization
4External JavaScript files can store complex data objects that integrate seamlessly with HTML through script tag linking
5Bracket notation for object property access is essential when using dynamic variables as property names
6DOM manipulation through getElementById and innerHTML allows precise control over page content updates
7Console debugging tools like console.dir provide detailed object property inspection during development
8Strategic file naming conventions enable dynamic asset loading through string concatenation with user selections

RELATED ARTICLES