More Javascript

Janyl Jumadinova

March 19, 2025

The DOM (Document Object Model)

  • Represents the structure of a webpage as a tree
  • JavaScript can manipulate HTML elements via the DOM
  • Example:
let heading = document.querySelector("h1");
heading.textContent = "Hello, DOM!";

Selecting Elements

  • document.getElementById("id")
  • document.querySelector(".class or #id")
  • document.querySelectorAll("tag")

Modifying the DOM

  • Changing text content:
document.querySelector("p").textContent = "New paragraph!";
  • Adding elements:
let newDiv = document.createElement("div");
newDiv.textContent = "I'm a new div!";
document.body.appendChild(newDiv);

Handling Events

  • JavaScript listens for user interactions
  • Example event listener:
document.querySelector("button").addEventListener("click", () => {
  alert("Button clicked!");
});

Common Events

  • click
  • mouseover
  • keydown
  • submit

Event Objects

  • Event handlers receive an event object
  • Example:
document.addEventListener("keydown", (event) => {
  console.log("Key pressed:", event.key);
});
  • Properties of event objects:
    • event.type (e.g., “click”, “keydown”)
    • event.target (element that triggered event)
    • event.clientX / event.clientY (mouse position)

Event Propagation

  • Bubbling: Event travels from the target up to the root
  • Capturing: Event travels from the root to the target
  • Example:
document.querySelector("div").addEventListener("click", (event) => {
  console.log("Div clicked");
}, true); // Use 'true' for capturing phase

Preventing Default Behavior

  • Some events have default behaviors (e.g., form submission)
  • Use event.preventDefault() to stop it
document.querySelector("form").addEventListener("submit", (event) => {
  event.preventDefault();
  console.log("Form submission prevented");
});

Fetching Data (HTTP Requests)

  • Using fetch():
fetch("https://some.place.com/posts/1")
  .then(response => response.json())
  .then(data => console.log(data));
  • Handling errors:
fetch("https://some.place.com/posts/1")
  .then(response => {
    if (!response.ok) {
      throw new Error("Network response was messed up");
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error("Fetch error:", error));

Async/Await

  • Simplifies handling asynchronous operations:
async function fetchData() {
  try {
    let response = await fetch("https://some.place.com/posts/1");
    if (!response.ok) {
      throw new Error("Network response was not ok");
    }
    let data = await response.json();
    console.log(data);
  } catch (error) {
    console.error("Fetch error:", error);
  }
}
fetchData();

Handling Form Data

  • Sending data using fetch():
async function sendData() {
  let response = await fetch("https://example.com/api", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ name: "John", age: 30 })
  });
  let result = await response.json();
  console.log(result);
}
sendData();

Introduction to Node.js

  • Node.js is a JavaScript runtime built on Chrome’s V8 engine
  • It allows running JavaScript outside the browser
  • Used for building backend applications and servers

Installing Node.js

  • Download and install from nodejs.org
  • Verify installation:
node -v  # Check Node.js version
npm -v   # Check npm (Node Package Manager) version

Why Use Node.js?

  • Enables JavaScript for server-side development
  • Handles asynchronous tasks efficiently
  • Works well for APIs, real-time apps, and automation
  • Example: A simple HTTP server
const http = require("http");

const server = http.createServer((req, res) => {
  res.writeHead(200, { "Content-Type": "text/plain" });
  res.end("Hello, Node.js!");
});

server.listen(3000, () => console.log("Server running on port 3000"));