JS Intro: DOM + Events

Foundations · Prereqs: F-HTML-001
--- theme: seriph title: "JS Intro: DOM + Events" info: "Module F-JS-001: document.querySelector, addEventListener, modifying text/style, basic event types" --- # JavaScript Intro: DOM + Events Make the page move. --- # 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 and Java are completely different languages despite the similar name. --- # Adding JavaScript to HTML ```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>` > AI tip: AI sometimes generates `onclick="..."` attributes in HTML. Always use `addEventListener` instead, as shown in this deck. --- layout: center --- # 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**: ```js // 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: ```js // Old way (still common) document.getElementById('intro') // Modern way (same result, more flexible) document.querySelector('#intro') ``` `querySelector` works with **any CSS selector**, so we will use it for everything. > AI tip: AI often generates `document.getElementById('intro')`. It works, but `querySelector('#intro')` is more flexible. Either is fine. --- # Try It: Open Console (F12) On any webpage, open DevTools Console and type: ```js document.querySelector('h1') ``` You'll see the first `<h1>` on the page highlighted. Now try: ```js document.querySelector('h1').textContent ``` You just **read** from the DOM. Next: **changing** it. --- # Changing the Page ```js // 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! --- layout: center --- # 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: ```js // 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. > AI tip: AI usually writes arrow functions (Style 3). If it looks unfamiliar, mentally read `() => { }` as `function() { }`. ```js // 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', () => { ... }); ``` --- # Example: Toggle Visibility ```html <button id="toggleBtn">Show/Hide</button> <div id="box">This content can be toggled</div> ``` ```js const button = document.querySelector('#toggleBtn'); const box = document.querySelector('#box'); button.addEventListener('click', function() { box.classList.toggle('hidden'); }); ``` ```css .hidden { display: none; } ``` --- # Example: Character Counter ```html <textarea id="message"></textarea> <p>Characters: <span id="count">0</span></p> ``` ```js 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: ```js console.log('Hello'); console.log(document.querySelector('h1')); ``` Use it to check values, find bugs, and understand code. > **F12 > Console tab**: use it constantly! --- # 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 ```js // 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`. > AI tip: AI sometimes uses `innerHTML` when `textContent` would be safer. Use `textContent` for plain text to avoid security issues. --- # Your Turn Download the starter file from the course website and save it as `js-demo.html` in your course repo. 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 > Do not worry about breaking things. You can always re-download the file. --- # Learn More - [MDN: DOM Introduction](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction) - [MDN: Events](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events) - [JavaScript.info: DOM](https://javascript.info/document)

Topics Covered

  • document.querySelector
  • addEventListener
  • modifying text/style
  • basic event types

Content Slides Open fullscreen ↗

Taught In