INF-250: Web Design and Development — JavaScript Events and Dynamic Elements

Announcements

Quiz #4 due this Sunday.

Assignment #3 due next Sunday.

Final project due on May 3rd - find details on Blackboard.

Review

//the document objects holds all the information about the HTML on the page
console.log(document);

//use it to create a JS variable that references an HTML element
const heading = document.querySelector("h1");

//modify the element using element.textContent
heading.textContent = "New Heading"

//modify CSS styles using element.style.propertyName
heading.style.color = 'red';
heading.style.fontSize = "32px";

This week we will keep learning how to make our pages more interactive by talking about:

  • event listeners: addEventListener()
  • keyboard events: keydown and keyup
  • creating new elements with JavaScript: document.createElement()

What Is an Event Listener?

An event is something that happens in the browser: a click, a key press, a page load, and more. An event listener tells JavaScript to watch for that event.

element.addEventListener("eventName", function() {
    // code to run when the event happens
});

Here is a simple button example:

const button = document.querySelector("#colorBtn");
const text = document.querySelector("#mainText");

button.addEventListener("click", function() {
    text.style.color = "crimson";
});
addEventListener keeps your JavaScript in your script file instead of mixing it into your HTML with onclick.

Why We Use DOMContentLoaded

JavaScript can run before the browser has finished building the page. If we try to select an element too early, JavaScript may not find it.

<script>
  let btn = document.getElementById('btn');
  btn.addEventListener('click', function() {
      // handle the click event
      console.log('clicked');
  });
</script>


<button id="btn">Click Me!</button>

View on CodePen

A safer pattern is to wait until the DOM is ready before selecting elements and attaching listeners.

Notice that this listener is attached to the document object.

Think of it as saying: “Do not start until the page is ready.”

It's good practice to put all of your JavaScript inside a DOMContentLoaded listener.

<script>
document.addEventListener('DOMContentLoaded', function(){
    let btn = document.getElementById('btn');
    btn.addEventListener('click', function() {
        // handle the click event
        console.log('clicked');
    });
  })
</script>


<button id="btn">Click Me!</button>

View on CodePen

The Event Object

Every time an event fires, JavaScript automatically creates an event object and passes it to your callback function. It contains details about what just happened — what kind of event it was, which element triggered it, which key was pressed, and more.

You can name the parameter anything, but event or e are the most common conventions.

element.addEventListener("click", function(event) {
    console.log(event.type);   // "click"
    console.log(event.target); // the element that was clicked
});

Two properties you will use constantly:

  • event.type — the name of the event that fired (e.g. "click", "keydown").
  • event.target — the specific element the event happened on.

event.target is especially useful when you attach one listener to a parent and need to know which child was actually clicked:

document.addEventListener("click", function(event) {
    console.log("You clicked:", event.target);
    console.log("Tag name:", event.target.tagName);
});
The event object is always there, even when you don't name it. You only need to add the parameter when you want to use it.

Keyboard Events: keydown and keyup

document.addEventListener("keydown", function(event) {
    console.log("Key pressed:", event.key);
});
document.addEventListener("keyup", function(event) {
    console.log("Key released:", event.key);
});
  • keydown fires the moment a key is pressed down.
  • keyup fires when the key is released.

The event.key property tells you exactly which key was pressed, as a string. Here are some common values you will check for:

  • "Enter" — the Enter / Return key
  • "Escape" — the Escape key
  • "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"
  • "a" through "z" — letter keys (lowercase)
document.addEventListener("keydown", function(event) {
    if (event.key === "Enter") {
        console.log("Enter was pressed");
    }
    if (event.key === "Escape") {
        console.log("Escape was pressed");
    }
    if (event.key === "ArrowUp") {
        console.log("Up arrow was pressed");
    }
});

Creating Elements with JavaScript

So far we have changed elements that already exist. We can also create brand new ones with JavaScript and insert them into the page.

const li = document.createElement("li");
li.textContent = "Finish homework";

document.querySelector("#taskList").appendChild(li);

This happens in three steps:

  1. document.createElement("li") — creates a new <li> element. At this point it only exists in memory. It is not on the page yet and the user cannot see it.
  2. li.textContent = "Finish homework" — sets the text inside the element, still in memory.
  3. appendChild(li) — this is what actually puts the element onto the page. It adds the new element as the last child of the target element. In this example, the new <li> appears at the bottom of #taskList.
Think of it like writing something on a sticky note (createElement), adding text to it (textContent), and then sticking it on the wall (appendChild). The note only becomes visible on the wall at the last step.

Guided Project: Interactive Task List

We are going to start a small project together. The page will let the user:

  • type a task into an input box
  • add that task to a list by clicking a button or pressing Enter
  • see the task appear in a list below

Independent Work

  1. Make sure tasks can be added with both the button and the Enter key.
  2. Prevent blank tasks from being added.
  3. Click a task to remove it — call .remove() on the element inside its click listener:
    // Call .remove() on the element itself
    li.addEventListener("click", function() {
        li.remove();
    });
  4. Add a Clear All button — set innerHTML = "" on the list to wipe every child at once:
  5. Style tasks differently when hovered
  6. Add a heading that shows how many tasks exist

Resources