Week 6: JavaScript and the DOM

INFO 253A: Front-end Web Architecture

Kay Ashaolu

JavaScript Chapter 7: DOM Manipulation

Introduction to the DOM

  • DOM: Document Object Model
  • Interface that allows scripts to update content, structure, and style
  • Represents the page so that programs can change the document structure, style, and content

Visualizing the DOM

  • The DOM is a tree structure of nodes
  • Each element, attribute, and text is a node
  • Example HTML:
  <!DOCTYPE html>
  <html>
    <head>
      <title>My Page</title>
    </head>
    <body>
      <div id="main">
        <h1 class="header">Welcome</h1>
        <p>Hello, World!</p>
      </div>
    </body>
  </html>

The Window and Document Objects

  • window: The global object representing the browser window
  • document: Represents the loaded HTML document
  • Accessing the document object:
  console.log(window.document);
  console.dir(document);

Exploring the Document Object

  • The document object has properties and methods to interact with the DOM

  • Examples:

    • document.body
    • document.title
    • document.URL
  • Methods to select elements, create elements, and more

Selecting Elements by ID

  • Use document.getElementById(id) to select an element
  • Returns the element with the specified id
 <h1 id="app-title">Shopping List</h1>
const title = document.getElementById('app-title');
console.log(title.innerText); // Outputs: Shopping List

Modifying Element Content

  • Change text content:
 title.innerText = 'My Shopping List';
  • Change HTML content:
 title.innerHTML = '<em>My Shopping List</em>';

Selecting Elements with Query Selectors

  • document.querySelector(selector)

    • Selects the first element that matches the CSS selector
 const header = document.querySelector('h1');
 const mainDiv = document.querySelector('#main');
 const items = document.querySelector('.items');

Selecting Multiple Elements

  • document.querySelectorAll(selector)

    • Selects all elements that match the CSS selector
    • Returns a NodeList
 const listItems = document.querySelectorAll('.item');
 listItems.forEach((item) => {
   console.log(item.innerText);
 });

Traversing the DOM: Parent and Children

  • Parent Element
 const child = document.querySelector('.child');
 const parent = child.parentElement;
  • Child Elements
 const parent = document.querySelector('.parent');
 const children = parent.children;
 console.log(children); // HTMLCollection of child elements

Traversing the DOM: Siblings

  • Next Sibling
 const item = document.querySelector('.item');
 const nextItem = item.nextElementSibling;
  • Previous Sibling
 const item = document.querySelector('.item');
 const prevItem = item.previousElementSibling;

Creating and Appending Elements

  • Create an element
 const newDiv = document.createElement('div');
  • Add content and attributes
 newDiv.id = 'new-id';
 newDiv.className = 'new-class';
 newDiv.textContent = 'Hello World';
  • Append to the DOM
 document.body.appendChild(newDiv);

Creating Elements: Best Practices

  • Prefer creating text nodes over using innerText
 const textNode = document.createTextNode('Hello World');
 newDiv.appendChild(textNode);
  • More efficient and avoids potential security risks

Inserting Elements at Specific Positions

  • insertAdjacentElement(position, element)

    • Positions:

      • 'beforebegin'
      • 'afterbegin'
      • 'beforeend'
      • 'afterend'
 const target = document.querySelector('.target');
 target.insertAdjacentElement('beforebegin', newDiv);

Replacing Elements

  • replaceWith(newElement)
 const oldItem = document.querySelector('.old-item');
 const newItem = document.createElement('div');
 newItem.textContent = 'New Item';
 oldItem.replaceWith(newItem);
  • parent.replaceChild(newChild, oldChild)
 const parent = document.querySelector('.parent');
 parent.replaceChild(newItem, oldItem);

Removing Elements

  • remove() method
 const item = document.querySelector('.item');
 item.remove();
  • removeChild() method
 const list = document.querySelector('ul');
 const item = document.querySelector('li');
 list.removeChild(item);

Manipulating Attributes

  • Get an attribute
 const link = document.querySelector('a');
 const href = link.getAttribute('href');
  • Set an attribute
 link.setAttribute('href', 'https://www.example.com');
  • Remove an attribute
 link.removeAttribute('target');

Manipulating Classes

  • classList property

    • Add a class
   element.classList.add('active');
  • Remove a class
 element.classList.remove('active');
  • Toggle a class
 element.classList.toggle('active');

Changing Styles Directly

  • Modify inline styles using the style property
 element.style.color = 'red';
 element.style.backgroundColor = '#f4f4f4';
  • Remember to use camelCase for multi-word properties

Understanding Node Types

  • Element Nodes: Represent HTML elements
  • Text Nodes: Contain text content
  • Comment Nodes: Represent comments in the HTML
  • Accessing All Child Nodes
 const parent = document.querySelector('.parent');
 const nodes = parent.childNodes; // Includes text and comment nodes

Traversing All Nodes

  • Use properties like:

    • firstChild
    • lastChild
    • nextSibling
    • previousSibling
  • Includes text and comment nodes, not just elements

Efficient DOM Manipulation

  • Minimize Reflows and Repaints

    • Batch DOM updates
    • Modify elements off-DOM when possible
  • Use Document Fragments

 const fragment = document.createDocumentFragment();
 // Add elements to fragment
 document.body.appendChild(fragment);

Best Practices

  • Avoid using innerHTML when possible

    • Can lead to security risks (e.g., XSS attacks)
    • Use DOM methods instead
  • Use Event Delegation

    • Attach events to parent elements to handle events for multiple child elements

The Role of the DOM in Web Architecture

  • Central to Client-Side Scripting

    • Enables dynamic content updates
    • Forms the basis for modern web applications
  • Interacts with APIs and Frameworks

    • Understanding the DOM is crucial for React, Angular, Vue, etc.

Summary

  • The DOM allows dynamic interaction with web pages
  • You can select, create, modify, and remove elements
  • Traversing the DOM helps in navigating between elements
  • Manipulating the DOM efficiently is key to performance

JavaScript Chapter 8: Events

What Are Events?

  • Events are actions or occurrences detected by the system.
  • User interactions: clicks, typing, mouse movements.
  • System events: page loading, resource fetching.

Role of Events in Web Architecture

  • Events drive interactivity and responsiveness.
  • Enable dynamic content updates without page reloads.
  • Fundamental to Single Page Applications (SPAs).

Adding Event Listeners

  • Event listeners connect code to user actions.
  • Syntax:
 element.addEventListener('eventType', handlerFunction);
  • Example:
 document.getElementById('btn').addEventListener('click', handleClick);

The Event Object

  • Provides details about the event.
  • Accessible within event handler functions.
  • Key properties:
    • target: element that triggered the event.
    • type: type of the event.
    • timestamp: time at which the event occurred.

Mouse Events in Web Architecture

  • Capture user interactions with pointing devices.
  • Common mouse events:
    • click
    • dblclick
    • mouseover / mouseout
    • mousedown / mouseup
  • Example:
 element.addEventListener('mouseover', function(event) {
   event.target.style.backgroundColor = 'yellow';
 });

Keyboard Events and Key Properties

  • Capture user input from the keyboard.
  • Events:
    • keydown: when a key is pressed down.
    • keyup: when a key is released.
    • keypress: when a character is generated.
  • Accessing key information:
    • event.key: value of the key pressed.
    • event.code: physical key on the keyboard.

Handling Input Events

  • Respond to changes in input fields.
  • input event fires when value changes.
  • Example:
 inputField.addEventListener('input', function(event) {
   console.log('Current value:', event.target.value);
 });

Form Submission and FormData

  • Handling form submissions without page reload.
  • Use event.preventDefault() to stop default behavior.
  • Access form data using FormData object.
 form.addEventListener('submit', function(event) {
   event.preventDefault();
   const data = new FormData(event.target);
   console.log('Form data:', data.get('username'));
 });

Event Bubbling and Propagation

  • Events propagate through the DOM tree.
  • Event Bubbling: Event moves from target up to ancestors.
  • Event Capturing: Event moves from ancestors down to target.
  • Can affect how events are handled in complex DOM structures.

Event Delegation

  • Efficient way to handle events on multiple elements.
  • Attach a single event listener to a parent element.
  • Use event.target to identify the clicked element.
  • Example:
 list.addEventListener('click', function(event) {
   if (event.target.matches('li')) {
     event.target.classList.toggle('selected');
   }
 });

Managing Window Events

  • The window object represents the browser window.
  • Common window events:
    • load: when the page has fully loaded.
    • resize: when the window is resized.
    • scroll: when the document is scrolled.
  • Example:
 window.addEventListener('resize', function() {
   console.log('Window resized to', window.innerWidth, 'x', window.innerHeight);
 });

Best Practices in Event Handling

  • Use event delegation to improve performance.
  • Clean up event listeners when elements are removed.
  • Be cautious with event propagation.
  • Avoid inline event handlers in HTML.

Events in Modern Web Applications

  • Events are central to frameworks like React, Vue, Angular.
  • Understanding native events helps with framework-specific events.
  • Essential for creating interactive, user-friendly interfaces.

Conclusion

  • Events are integral to front-end web architecture.
  • Enable dynamic and responsive user experiences.
  • Mastery of events enhances ability to build complex applications.

Week 6 - JavaScript in the Browser

By kayashaolu

Week 6 - JavaScript in the Browser

Course Website: https://www.ischool.berkeley.edu/courses/info/253a

  • 74