Dynamically Changing Content with Custom Objects

Free JavaScript Tutorial

Enhance your JavaScript skills with this tutorial, covering topics such as referencing the menu, listening for when the menu is changed, getting the chosen value, loading in data from external files, and dynamically changing the information on the page.

This exercise is excerpted from Noble Desktop’s JavaScript for Front-End training materials and is compatible with JavaScript updates through 2023. To learn current skills in JavaScript with hands-on training, check out our Front-End Web Development Certificate, Full-Stack Web Development Certificate, and coding classes in-person and live online.

Topics covered in this JavaScript tutorial:

Referencing the Menu, Listening For When the Menu is Changed & Getting the Chosen Value, Loading in Data from an External File, Dynamically Changing Info on the Page

Exercise Preview

preview custom objects

Exercise Overview

In this exercise, you’ll use JavaScript objects to dynamically update content without having to reload the page. In other words, you’ll have a single page where the user makes a selection and the info on the page will update without having to reload.

JavaScript Development Certificate: Live & Hands-on, In NYC or Online, 0% Financing, 1-on-1 Mentoring, Free Retake, Job Prep. Named a Top Bootcamp by Forbes, Fortune, & Time Out. Noble Desktop. Learn More.

Getting Started

  1. For this exercise we’ll be working with the State-Facts folder located in Desktop > Class Files > JavaScript Class. Open that folder in your code editor if it allows you to (like Visual Studio Code does).
  2. In your code editor, open index.html from the State-Facts folder.
  3. Preview index.html in Chrome. (We’ll be using its DevTools.)

    When a user goes into the Choose a State menu at the top and chooses a state, we want them to see the info for it (without loading a new page). That’s the functionality we’re going to build.

  4. Leave the page open in Chrome so we can come back to it later.

Referencing the Menu

  1. Return to index.html in your code editor.
  2. On line 17, find the select tag which defines the menu.

    • Notice there is an option with a value attribute for each state.
    • We will get the value from the option the user has chosen and we’ll use that value to access stored data for each state.
  3. Before the closing </body> tag, add the following bold code to save a reference to that select element (the menu):

       </div>
       <script>
          let stateList = document.getElementById('state-list');
       </script>
    </body>
    
  4. Let’s output it to the Console so we can look at it more closely. Add the following bold code:

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

    • In the Console, the entire select element will appear.
    • Click the arrow to its left of the code to expand it and notice all the options.

    Eventually we want to get the value of what the user selects.

  7. Back in your code editor, change log to dir:

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

    • In the Console, now you’ll see select#state-list instead of the HTML.
    • Click the arrow to its left of the code to expand it. Scroll down below the list of options. Here you see the many properties, etc. you can use in JS.
    • Scroll down to find value. The current value is "usa" but when the user selects a state the value will be a 2-letter abbreviation of whichever state they chose, such as "ny" or "nj". This value is the info we need to get.

    TIP: To clear the Console, you can hit Cmd–K (Mac) or Ctrl–L (Windows).

  9. Back in your code editor, add .value as shown below:

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

    In the Console you should see usa (which will be a 2-letter state abbreviation once the user chooses something from the menu).

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

Previously we’ve created event listeners for click or mouseover. Let’s create one for when the user changes the menu.

  1. Event listeners need a function to run when the event is triggered, so wrap the console.dir in a function:

    let stateList = document.getElementById('state-list');
    function showStateInfo() {
       console.dir(stateList.value);
    };
    
  2. Now add an event listener that will trigger that function:

    let stateList = document.getElementById('state-list');
    function showStateInfo() {
       console.dir(stateList.value);
    };
    stateList.addEventListener('change', showStateInfo);
    
  3. Outside of a function, this refers to the global Window object. But, as we’ve previously seen, inside a function, this refers to the object that called the function. Change stateList to this as shown below:

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

    • Choose a state from the menu.
    • In the Console you should see the value of whatever state you chose.
    • Choose another state and it will again show the value for the state you chose.

    Now that we know the event listener is working, we have to work on what happens in that showStateInfo() function.

Loading in the State Data from an External File

We have an object that we’re providing to you, which contains info about each state. When our user chooses a state, we want to provide them with that info. Let’s take a look at the object you’ll pull the data from.

  1. Back in your code editor, in the js folder open state-data.js.

    In this large file, we’ve declared an object that we can access by referencing the variable stateData. As you can see on line 1, the variable’s value is wrapped in {}, which indicates it’s an object.

    Its curly braces wrap its many properties (which are all objects). There is a child object for each state (an object within a parent object), which each contain multiple properties (name, abbr, capitol, etc) with appropriate values.

  2. In order to use this object, we must load it into our page by linking to this JS file. In your code editor, switch back to index.html.

  3. Above the current script tag, add in the following link to that js file:

    </div>
    <script src="js/state-data.js"></script>
    <script>
    
  4. Now let’s see how to access the properties of the stateData object by adding the following bold code in the script tag:

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

    In the Console you should see New York

  6. Switch back to your code editor.
  7. Let’s see another way to write this same reference. Change ny to ['ny'] as shown below in bold:

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

    In the Console you again should see New York.

    This alternate syntax is useful when you need to pass in a variable into the square brackets [] which doesn’t work in the other dot syntax. You’ll see how this will be useful in just a moment.

Dynamically Changing Info on the Page

We’re finally ready to start changing the content on the page. Let’s start with changing the state name below the image.

  1. Back in your code editor, around line 76, find the info-name figcaption. We’ll set this to the name of whichever state the user chooses.

  2. Change the console.dir as follows:

    function showStateInfo() {
       let selectedState = this.value;
    };
    
  3. Cut the console.log(stateData['ny'].name); and paste it into the function:

    function showStateInfo() {
       let selectedState = this.value;
       console.log(stateData['ny'].name);
    };
    
  4. Change the console.log as follows so it puts the name into the info-name paragraph on the page:

    function showStateInfo() {
       let selectedState = this.value;
       document.getElementById('info-name').innerHTML = stateData['ny'].name;
    };
    
  5. Currently we’ve hard coded ny as the state. Change that to the selectedState as shown below in bold:

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

    NOTE: The value of selectedState is this.value but the dot syntax stateData.this.value would not work. Because this.value is a dynamic property, it must go in the square brackets.

  6. Save and reload the page in Chrome.

    • Choose a state from the menu and notice the state name below the image changes!
    • Next we’ll need to change the rest of the info on the page.

Dynamically Changing the Rest of the Page Info

  1. Switch back to your code editor.
  2. The easiest way for us to set the other values is by copying/pasting the code we already wrote. Copy the following line:

    document.getElementById('info-name').innerHTML = stateData[selectedState].name;
    
  3. Paste a copy as a new line, directly below.
  4. The next value is the state abbreviation, so edit the code as shown below:

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

    NOTE: In state-data.js, each state in the parent stateData object has a key named abbr that stores a value for the state abbreviation.

  5. Save and reload the page in Chrome.

    • Choose a state from the menu.
    • Now you should see the text for Abbreviation change (as well as the state’s name below the image).
  6. Return to your code editor.
  7. Now that you see how this works, doing the rest would be a lot of copy/paste/edit a name. We’ll save you time by providing the code with everything already typed out.

    In the snippets folder, open change-function-code.js.

  8. Copy all the code.
  9. Switch back to index.html and paste the new code below the 2 lines of document.getElementById you already wrote.
  10. Save and reload the page in Chrome.

    Choose a state from the menu and you should see all the text info update!

  11. All that’s left for us to do is change the state image. In your code editor’s file explorer sidebar, open the img folder to see all the state images.

    Notice that we specifically named them to match the state abbreviations.

  12. In index.html in your code editor, add the following bold code to get the state image to change:

    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.

    Choose a state from the menu and you should see the state image change, along with the rest of the info.

photo of Dan Rodney

Dan Rodney

Dan Rodney has been a designer and web developer for over 20 years. He creates coursework for Noble Desktop and teaches classes. In his spare time Dan also writes scripts for InDesign (Make Book JacketProper Fraction Pro, and more). Dan teaches just about anything web, video, or print related: HTML, CSS, JavaScript, Figma, Adobe XD, After Effects, Premiere Pro, Photoshop, Illustrator, InDesign, and more.

More articles by Dan Rodney

How to Learn JavaScript

Master JavaScript with hands-on training. JavaScript is one of the world's most widely-used coding languages. Learn JavaScript and its libraries to start creating interactive websites and mobile apps.

Yelp Facebook LinkedIn YouTube Twitter Instagram