Skip to main content
April 1, 2026Dan Rodney/10 min read

Dynamically Changing Content with Custom Objects

Master Dynamic Content Updates with JavaScript Objects

Tutorial Focus

This hands-on tutorial teaches you to create dynamic web pages that update content without reloading, using JavaScript objects and the 'this' keyword for efficient DOM manipulation.

Topics Covered in This JavaScript & jQuery Tutorial:

Master dynamic web content creation by learning to check select menu functionality, retrieve user-selected values, dynamically update state names, and programmatically modify all associated content elements.

Learning Path Overview

1

Select Menu Setup

Learn to check and test select menu functionality using browser DevTools

2

Value Extraction

Master retrieving selected values from form elements

3

JavaScript 'This' Keyword

Understand context and scope in event handlers

4

Dynamic Updates

Implement real-time content changes using object data

Exercise Preview

ex prev custom objects

Exercise Overview

In this comprehensive exercise, you'll harness the power of JavaScript objects to create seamless, dynamic user experiences without page reloads. This technique forms the foundation of modern single-page applications (SPAs) and is essential for creating responsive, interactive web interfaces that users expect in 2026.

You'll build an intelligent state facts page where user selections instantly trigger content updates—demonstrating the core principles behind popular frameworks like React, Vue, and Angular. This hands-on approach will solidify your understanding of DOM manipulation, event handling, and object-based data management.

Getting Started

  1. Launch your preferred code editor if it's not already running.
  2. Close any previously opened files to maintain a clean workspace.
  3. Navigate to the State-Facts folder located in Desktop > Class Files > yourname-JavaScript jQuery Class. For optimal workflow, open this entire folder in your editor (Visual Studio Code, WebStorm, or similar IDEs support this feature).
  4. Open index.html from the State-Facts directory.
  5. Preview index.html in Chrome—we'll leverage its powerful DevTools throughout this exercise.

    Your objective is to transform this static page into a dynamic interface where users can select any state from the Choose a State dropdown and instantly view comprehensive information without triggering a page refresh. This approach significantly improves user experience and reduces server load.

  6. Keep the browser tab open for seamless testing as you progress through the exercise.

Required Tools and Setup

Code Editor

Visual Studio Code or similar editor with folder browsing capabilities for managing project files efficiently.

Chrome Browser

Essential for DevTools debugging and console testing. We'll use its JavaScript console extensively throughout the tutorial.

Project Files

State-Facts folder containing HTML, JavaScript, and image assets. All files are pre-structured for the exercise.

Checking the Functionality of the Select Menu

Before implementing dynamic functionality, we need to verify our select element is properly configured and accessible via JavaScript. This debugging approach will serve you well in professional development environments.

  1. Return to index.html in your code editor.
  2. Locate the select element on line 16. Notice each option contains a strategic value attribute corresponding to state abbreviations. These values will serve as keys for accessing our data object—a common pattern in data-driven applications.
  3. Now we'll test the select menu using Chrome's Console, an invaluable tool for debugging and prototyping JavaScript functionality. Switch to Chrome.

    Ensure index.html remains open in your browser.

  4. Open Chrome's Developer Console using Cmd–Opt–J (Mac) or CTRL–Shift–J (Windows).
  5. Create a reference variable for easier manipulation. In the Console, enter:

    var stateList = document.getElementById('state-list');
  6. Press Return (Mac) or Enter (Windows) to execute.
  7. Verify the operation succeeded by typing stateList; and pressing Return (Mac) or Enter (Windows).
  8. The Console will display the select element. Click the expandable arrow to explore its properties and nested option elements—this inspection technique is crucial for understanding DOM structure.

    NOTE: Clear the Console anytime using Cmd–K (Mac) or CTRL–L (Windows) for better visibility.

  9. Now we'll attach an event listener to monitor state changes. Enter the following code block, using Shift–Return (Mac) or Shift–Enter (Windows) for multi-line input:

    stateList.onchange = function() {
       console.log('changed!');
    };
  10. Press Return (Mac) or Enter (Windows) to implement the event handler.
  11. Test the functionality by selecting different states from the dropdown menu.

    The Console should display changed! with an incrementing counter, confirming your event listener is working correctly. This real-time feedback loop is essential for validating JavaScript functionality.

  12. Return to index.html in your code editor.
  13. Implement the tested functionality in your HTML by adding this script block before the closing </body> tag (approximately line 92):

    </div>
       <script>
          document.getElementById('state-list').onchange = function() {
    
          };
       </script>
    </body>
  14. Save your changes to preserve your progress.

DevTools Console Commands

Use Cmd-Opt-J (Mac) or CTRL-Shift-J (Windows) to open Chrome DevTools Console. Clear console with Cmd-K (Mac) or CTRL-L (Windows) for better visibility.

Console Testing Process

1

Save Element to Variable

Store the select menu in a variable using document.getElementById for easier access

2

Add Change Event

Attach onchange event handler to test menu functionality in real-time

3

Verify Functionality

Test by selecting different states and observing console output

Getting the Chosen Value

With our event handler confirmed, we'll now capture the user's selection. Understanding how to extract values from form elements is fundamental to creating interactive web applications.

  1. Switch back to Chrome, keeping the current page loaded to maintain your Console variables.

  2. Explore the select element's properties to identify the value property. Type:

    console.dir(stateList);
  3. Expand the select#state-list object by clicking its arrow.
  4. Scroll through the properties to locate value. This property contains the currently selected option's value attribute—in our case, the two-letter state abbreviation like "ak" for Alaska or "nj" for New Jersey.

    Understanding object properties through console inspection is a critical debugging skill that will accelerate your development workflow.

  5. Return to index.html in your code editor.

  6. Add test code to your event handler (around line 94):

    <script>
       document.getElementById('state-list').onchange = function() {
          console.log(value);
       };
    </script>
  7. Save the file and test your changes.

  8. Switch to Chrome and reload index.html.

  9. Select a state from the dropdown. You'll encounter an error: Uncaught ReferenceError: value is not defined.

  10. This error illustrates a crucial JavaScript concept: scope and context. The browser interprets value as a global variable rather than a property of our select element.

    Return to your code editor. We need to explicitly reference the select element's value property. While we could write document.getElementById('state-list').value, this approach is verbose and inefficient.

    Instead, we'll use JavaScript's this keyword, which refers to the object that triggered the event. This technique is fundamental to event-driven programming and object-oriented JavaScript.

  11. Update your code to properly capture the selected value:

    document.getElementById('state-list').onchange = function() {
       var selected = this.value;
       console.log(value);
    };
  12. Now reference the stored value instead of the undefined global:

    document.getElementById('state-list').onchange = function() {
       var selected = this.value;
       console.log(selected);
    };
  13. Save your changes.

  14. Reload index.html in Chrome.

  15. Test by selecting various states. The Console should now display each state's abbreviation without errors—confirming your value extraction is working correctly.

    Common Error Alert

    Using 'value' directly without proper context results in 'Uncaught ReferenceError: value is not defined' because the browser assumes it refers to the global object.

The JavaScript Keyword This

The this keyword in JavaScript functions similarly to demonstrative pronouns in natural language—it provides context-dependent reference to objects. Understanding this is crucial for professional JavaScript development, as its value depends entirely on the execution context.

In the global context, this refers to the window object. However, within event handlers like onchange or onclick, this refers to the HTML element that triggered the event. This behavior enables elegant, reusable code that adapts to different contexts.

Master this concept by exploring the comprehensive guide at tinyurl.com/javascript-keyword-this—it's essential knowledge for modern JavaScript development.

In JavaScript, we use the keyword this much the way we use the demonstrative 'this' in everyday natural language.
Understanding context is crucial for proper event handling and object manipulation in JavaScript applications.

Context Comparison: Global vs Event Handler

FeatureGlobal ContextEvent Handler Context
this refers toGlobal object/windowHTML element that owns the event
Usage examplewindow.propertythis.value (element's value)
Common mistakesAssuming global scopeForgetting element context
Recommended: Always consider the execution context when using 'this' keyword

Dynamically Changing the State Name Value

Now we'll transition from simple value extraction to sophisticated data manipulation using JavaScript objects. This approach scales far beyond basic form interactions, enabling you to manage complex data structures efficiently.

In previous exercises, you worked with limited option element data (value and textContent). Here, we'll demonstrate the power of object-based data storage, accessing rich information sets that mirror real-world application architectures.

  1. In your code editor, navigate to State-Facts > js and examine state-data.js.

    This file contains a comprehensive stateData object structured as nested key-value pairs. Line 1 shows the object declaration using {} syntax, with each state abbreviation serving as a property containing its own object of detailed information.

    This pattern—using objects to organize related data—is fundamental to modern JavaScript applications and forms the basis of JSON data structures used in APIs and databases.

  2. Return to index.html in your code editor.

  3. Locate the info-name paragraph around line 76—this will display our dynamically updated state names.

  4. Link the state data object to your HTML by adding the script reference above your existing script tag (around line 92):

    </div>
    <script src="js/state-data.js"></script>
    <script>

    This import grants access to the entire stateData object, unlocking rich information for each state. Proper script loading order is crucial—data must be available before your manipulation code executes.

  5. Test object accessibility by modifying your event handler (around line 96):

    document.getElementById('state-list').onchange = function() {
       var selected = this.value;
       console.log(stateData);
    };
  6. Save, switch to Chrome, and reload index.html.
  7. Select any state to see the complete stateData object logged:

    Object {usa: Object, al: Object, ak: Object, az: Object, ar: Object…}

    While this confirms successful object loading, we need to target specific state data rather than the entire collection.

  8. Refine your selection using bracket notation to access specific state objects:

    document.getElementById('state-list').onchange = function() {
       var selected = this.value;
       console.log(stateData[selected]);
    };
  9. Save, reload in Chrome, and test again.
  10. Now you'll see individual state objects like:

    Object {name: "Kansas", abbr: "KS", capitol: "Topeka", pop: "3,090,416", statehood: "1861"…}

    Excellent progress! The bracket notation stateData[selected] dynamically accesses object properties using variable values—a powerful technique for data-driven applications.

  11. Further refine your data access to retrieve specific properties:

    document.getElementById('state-list').onchange = function() {
       var selected = this.value;
       console.log(stateData[selected].name);
    };
  12. Save, reload, and test with multiple states.
  13. The Console now displays individual state names, demonstrating precise data extraction from complex objects.
  14. Return to your code editor for the final implementation step.
  15. Replace the console logging with actual DOM manipulation:

    document.getElementById('state-list').onchange = function() {
       var selected = this.value;
       stateData[selected].name;
    };
  16. Connect this data to your HTML element:

    document.getElementById('state-list').onchange = function() {
       var selected = this.value;
       document.getElementById('info-name').textContent = stateData[selected].name;
    };
  17. Save your changes.
  18. Switch to Chrome, reload index.html, and test.
  19. Select different states and watch the name below the map image update instantly. You've successfully implemented dynamic content updates without page refreshes—the foundation of modern web applications.

Object Structure Advantage

Unlike option elements with only two pieces of data (value and textContent), custom objects can store unlimited information including name, abbreviation, capitol, population, and statehood data.

Data Access Pattern

1

Link Data Source

Include state-data.js file to access the comprehensive stateData object

2

Access State Object

Use selected value as key to retrieve specific state data: stateData[selected]

3

Extract Property

Access individual properties like name using dot notation: stateData[selected].name

4

Update DOM Element

Set textContent of target element to display the retrieved data

Dynamically Changing the Rest of the Values

With the core concept mastered, we'll expand functionality to update all state information simultaneously. This comprehensive approach demonstrates scalable JavaScript patterns used in professional web development.

  1. Return to your code editor.
  2. Extend functionality by copying your successful implementation pattern:

    document.getElementById('info-name').textContent = stateData[selected].name;
  3. Paste this line directly below the original.
  4. Modify the duplicate to handle state abbreviations:

    document.getElementById('info-name').textContent = stateData[selected].name;
    document.getElementById('info-abbreviation').textContent = stateData[selected].abbr;

    Notice how the HTML element ID corresponds to info-abbreviation while the data property uses abbr—this separation allows for flexible naming conventions between your interface and data layers.

  5. Save and test in Chrome after reloading.
  6. Verify that both state name and abbreviation update when selecting different states.
  7. Continue expanding functionality by adding capitol information.
  8. Copy the abbreviation line and paste it below.
  9. Update for capitol data:

    document.getElementById('info-name').textContent = stateData[selected].name;
    document.getElementById('info-abbreviation').textContent = stateData[selected].abbr;
    document.getElementById('info-capitol').textContent = stateData[selected].capitol;

    Reference index.html around lines 75-88 for additional element IDs, and check state-data.js for available object properties.

  10. Save, reload, and test the expanding functionality.
  11. For efficiency, we'll use pre-written code to complete all remaining fields.
  12. Navigate to State-Facts > snippets and open change-function-code.txt.
  13. Copy all provided code.
  14. Return to index.html and select your three existing update lines.
  15. Replace them with the comprehensive code snippet.
  16. Save, reload in Chrome, and test.
  17. All textual information should now update dynamically when selecting states.
  18. The final enhancement involves updating the state image. Navigate to Desktop and explore the state-facts > img folder to see the naming convention—each image uses the state abbreviation as its filename.
  19. Return to index.html in your code editor.
  20. Add image updating functionality to your script:

    var selected = this.value;
    document.getElementById('info-pic').src = 'img/' + selected + '.jpg';
    document.getElementById('info-name').textContent = stateData[selected].name;
  21. Save your final changes.
  22. Test in Chrome after reloading.
  23. Select different states to see complete synchronization—image, name, abbreviation, capitol, population, and all other data should update instantly.

    Congratulations! You've built a fully functional, dynamic web application that demonstrates professional JavaScript techniques. This pattern scales to complex applications with thousands of data points and forms the foundation for modern single-page applications.

    For reference implementation, examine the completed files in Desktop > Class Files > yourname-JavaScript jQuery Class > Done-Files > State-Facts.

Implementation Checklist

0/5
Efficient Development Tip

Copy and paste similar code lines, then modify the element ID and object property. This reduces typing errors and speeds up development when updating multiple elements.

Key Takeaways

1JavaScript objects provide a powerful way to store and access multiple pieces of related data, far exceeding the limitations of simple HTML element attributes
2The 'this' keyword in JavaScript refers to different objects depending on context - in event handlers it refers to the HTML element that owns the event
3Chrome DevTools Console is essential for testing JavaScript functionality in real-time before implementing code in your source files
4Dynamic content updates without page reloads improve user experience by providing immediate feedback and maintaining application state
5String concatenation with selected values enables dynamic file path generation for images and other resources
6Using document.getElementById() with variables improves code readability and reduces repetitive DOM queries
7Event handlers like onchange provide the foundation for creating interactive web applications that respond to user input
8Proper error handling and testing in the console helps identify and resolve common JavaScript errors like undefined variable references

RELATED ARTICLES