Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 21

Dynamic Content and Style with User Actions

Recommended resources

Hello! Welcome back to our course on building your AI web application.

In our last lesson, you learned the essentials of the Document Object Model (DOM). You practiced selecting HTML elements and changing their content, attributes, and styles as soon as the page loaded. This was a crucial first step in making your page dynamic.

Today, we'll build on that foundation to achieve a key goal: making your webpage interactive. You'll learn how to make these content and style changes happen in response to user actions, like clicking a button or typing in a text field. This is the magic that separates a static document from a real web application.

By the end of this lesson, you will be able to connect your JavaScript code to user actions, allowing you to dynamically change what's on the page for a truly interactive experience.

Listening for User Actions: addEventListener

So, how do we tell our JavaScript to wait for the user to do something before it runs? We use something called an event listener.

Think of it like setting a simple alarm. You "attach" a listener to an HTML element (like a button) and tell it which "event" to listen for (like a click). You also give it a set of instructions—a JavaScript function—to run when that event happens.

The primary method for this is element.addEventListener(). Let's look at a clear, simple example.

DOM Manipulation in JavaScript – A Comprehensive ...

This article from freeCodeCamp clearly explains the concept of event listeners. We'll focus on the basic syntax for making your code run when a user clicks an element.

Read the section 'Events and Event Handling', focusing on the 'How to add event listeners' subsection. The example shows how to pop up an alert when a button is clicked. We will adapt this same pattern to change page content.

The basic structure looks like this:

// 1. Select the element
const myButton = document.querySelector('#myButton');

// 2. Define the function to run on the event
function whatToDoOnClick() {
    // Code to change content or style goes here
    console.log('Button was clicked!');
}

// 3. Add the event listener
myButton.addEventListener('click', whatToDoOnClick);

Here, we're telling myButton to listen for a click event and to execute the whatToDoOnClick function every time it happens.


Dynamically Changing Content Based on User Actions

Now, let's make this useful. Instead of just logging a message to the console, let's change the content on the page.

Imagine you have a paragraph and a button:

<p id="message">This is the original message.</p>
<button id="change-btn">Change Message</button>

You can use an event listener to change the paragraph's text when the button is clicked:

const messageParagraph = document.querySelector('#message');
const changeButton = document.querySelector('#change-btn');

changeButton.addEventListener('click', function() {
    messageParagraph.textContent = 'The message has been updated!';
});

This pattern is incredibly powerful. For your AI Writing Assistant, you'll need to take the text a user types into a <textarea> and do something with it. The next resource shows a similar idea.

DOM Manipulation in JavaScript – A Comprehensive ...

This next section of the same article demonstrates how to take text from an input box and display it elsewhere on the page. This is a core part of making your form interactive.

Read the subsection 'How to update form input values'. The example uses the input event, which fires every time the user types a character. We will adapt this concept for a button click event.

Using that principle, we can build the logic for our app:

  1. Select the <textarea> and the button.
  2. Add a click listener to the button.
  3. Inside the listener function, get the .value of the <textarea>.
  4. Do something with that value, like displaying it in another element.

Dynamically Changing Styles Based on User Actions

Changing content is great, but changing styles is what makes an application feel responsive and alive. The best way to do this is by adding or removing CSS classes.

In the last lesson, you learned about the classList property. When combined with event listeners, it becomes a powerful tool for dynamic styling. You can add(), remove(), or toggle() classes in response to user actions.

The following video provides an excellent, detailed example of using classList to dynamically apply styles.

JavaScript DOM Manipulation Mastery: A Comprehensive Guide

This video gives a fantastic demonstration of using classList to dynamically add and remove CSS classes based on different conditions, which is a professional way to manage styles.

Watch the segment from 00:48:00 to 00:54:08. Notice how classList.add() and conditional logic (if/else) are used to apply different styles to items in a list. The concept of using toggle() is also introduced, which is very useful.

For very simple, one-off style changes, you can also modify the style property directly. Just remember that CSS properties with hyphens (like background-color) become camelCase in JavaScript (backgroundColor).

Test your understanding!

You have a div with the ID #alert-box. You want to make its background color change to yellow when a button with the ID #show-alert is clicked. How would you write the JavaScript for this using the .style property?

Show answer
const alertBox = document.querySelector('#alert-box');
const showAlertButton = document.querySelector('#show-alert');

showAlertButton.addEventListener('click', function() {
    alertBox.style.backgroundColor = 'yellow';
});

Hands-On Project: A Dynamic Shopping List

It's time to put all these concepts together. Theory is important, but building something is the best way to learn. The Mozilla Developer Network (MDN), a top resource for web developers, has a perfect exercise for you. You will build a simple shopping list application that allows you to add and delete items.

This project will require you to:

  • Select existing elements (ul, input, button).
  • Listen for a click event on the "Add item" button.
  • Read the value from the input field.
  • Dynamically create new HTML elements (li, span, button).
  • Append these new elements to the page.
  • Add an event listener to the newly created delete buttons.

This is an excellent real-world application of today's lesson.

DOM scripting introduction - Learn web development | MDN

Follow the steps in this MDN tutorial to build your first fully interactive DOM manipulation project. This will solidify everything we've discussed today.

Go to the section 'Creating a dynamic shopping list'. Download their starting HTML file and write your JavaScript code as instructed. Follow the 12 steps to build the application. Don't worry if it feels challenging; take your time and refer back to the code examples in this lesson if you get stuck.


Conclusion

Excellent work today! You have bridged the gap between a static page and an interactive one. By combining DOM manipulation with event listeners, you now have the core skills to build a dynamic user interface.

Key Takeaways:

  • element.addEventListener('eventName', functionToRun) is the key to making JavaScript code run in response to user actions.
  • The click event is the most common event for user interactions with buttons and other elements.
  • Inside an event listener function, you can execute any DOM manipulation you've learned:
    • Change content with .textContent or .innerHTML.
    • Get user input with .value.
    • Change styles using .classList.toggle() or by modifying .style.
  • You can even create new elements and add event listeners to them, making your page grow and change dynamically.

You now understand how to respond to a user clicking a button. In our next lesson, we will formalize this knowledge by exploring event listeners in more detail. We'll look at other important event types, like the submit event for forms, and learn more about the event object itself. This will prepare you to capture user input from your form and get it ready to be processed.