JavaScript Intro

contain

What is JavaScript?

HTML gives your page structure. CSS gives it style.

JavaScript makes it do things.

  • Respond to clicks and input
  • Change content dynamically
  • Fetch data from servers
  • Build interactive applications

JavaScript ≠ Java (completely different languages!)

Adding JavaScript to HTML

<!-- At the bottom of <body> (recommended for now) -->
<body>
  <!-- your HTML content -->
  <script>
    // JavaScript code here
  </script>
</body>

Later, we'll use external files: <script src="script.js"></script>

You may see onclick="..." in HTML. This is an older style; we'll use addEventListener instead.

The DOM

What is the DOM?

When the browser loads HTML, it builds a tree in memory called the DOM.

JavaScript can read and change this tree.

document
└── html
    ├── head
    │   └── title
    └── body
        ├── h1
        ├── p
        └── button

Finding Elements

Use document.querySelector() with any CSS selector:

// By tag
document.querySelector('h1')

// By class
document.querySelector('.card')

// By ID
document.querySelector('#intro')

This returns the first matching element. Use querySelectorAll() for all matches.

Two Ways to Select by ID

You'll see both of these online and in AI-generated code:

// Old way (still common)
document.getElementById('intro')

// Modern way (same result, more flexible)
document.querySelector('#intro')

querySelector works with any CSS selector, so we'll use it for everything.

Try It: Open Console (F12)

On any webpage, open DevTools Console and type:

document.querySelector('h1')

You'll see the first <h1> on the page highlighted.

Now try:

document.querySelector('h1').textContent

You just read from the DOM. Next: changing it.

Changing the Page

// Change text
document.querySelector('h1').textContent = 'Hello!';

// Change style
document.querySelector('h1').style.color = 'red';

// Add/remove CSS class
document.querySelector('h1').classList.toggle('hidden');

Try these in the Console right now!

Events

What is an Event?

Events are actions that happen on the page:

  • User clicks a button
  • User types in an input
  • Mouse hovers over an element
  • A form is submitted

JavaScript can listen for these events and respond.

addEventListener

This is the core pattern. Remember it:

// 1. Find the element
const button = document.querySelector('button');

// 2. Listen for an event
button.addEventListener('click', function() {
  // 3. Do something
  alert('Button clicked!');
});

Three Syntaxes, Same Thing

AI tools and online examples use different styles. They all do the same thing:

// Style 1: anonymous function (clearest for beginners)
button.addEventListener('click', function() { ... });

// Style 2: named function (good for reuse)
function handleClick() { ... }
button.addEventListener('click', handleClick);

// Style 3: arrow function (you'll see this in AI code)
button.addEventListener('click', () => { ... });

How It Connects to the Demo

Remember the JS demo file you explored? Here's what was happening:

  1. document.querySelector(): finds elements on the page
  2. addEventListener('click', ...): waits for a click
  3. Inside the function: changes text, styles, or classes

That's the pattern for almost everything in JavaScript.

Example: Toggle Visibility

<button id="toggleBtn">Show/Hide</button>
<div id="box">This content can be toggled</div>
const button = document.querySelector('#toggleBtn');
const box = document.querySelector('#box');

button.addEventListener('click', function() {
  box.classList.toggle('hidden');
});
.hidden { display: none; }

Example: Character Counter

<textarea id="message"></textarea>
<p>Characters: <span id="count">0</span></p>
const textarea = document.querySelector('#message');
const counter = document.querySelector('#count');

textarea.addEventListener('input', function() {
  counter.textContent = textarea.value.length;
});

Debugging: console.log

Your best friend for understanding what's happening:

console.log('Hello');
console.log(document.querySelector('h1'));

Use it to check values, find bugs, and understand code.

F12 > Console tab: use it constantly!

Your Turn

Open the JS demo file in VS Code. Try these modifications:

  1. Change the text that appears when you click a button
  2. Change the color that gets applied
  3. Add a console.log() inside one of the event listeners to see when it fires

Don't worry about breaking things. You can always re-download the file.

Reference

Common Events

Event When it fires
click Element is clicked
mouseover / mouseout Mouse enters/leaves
keydown Key is pressed
submit Form is submitted
input Input value changes (every keystroke)
change Input loses focus after changing

More DOM Methods

// Change HTML content (careful with user input!)
element.innerHTML = '<em>Bold</em> text';

// Change attributes
element.setAttribute('src', 'new-image.jpg');

// Change multiple styles
element.style.cssText = 'color: red; font-size: 20px;';

CSS property names use camelCase in JS: background-color becomes backgroundColor

Learn More