OIM3690 - Web Technologies

contain

Introduction to JavaScript

What is JavaScript (JS)?

  • JavaScript was created in 1995 by Brendan Eich
  • Client-side JavaScript (Main focus of this course)
    • Runs in the browser.
    • Enables interactive web pages by:
      • Dynamically updating content.
      • Controlling multimedia.
      • Animating images, etc.
  • Server-side JavaScript (e.g., Node.js)
    • Runs outside the browser.
    • Used for building APIs, handling HTTP requests, accessing databases, etc.

How to Add JavaScript

  • Internal JavaScript
    • Written inside a <script> tag.
    • Best practice: Place it at the bottom of <body> to prevent blocking the page.
  • External JavaScript
    • JavaScript is stored in a separate file (.js).
    • Syntax: <script src="script.js" defer></script>
      • Use defer to ensure scripts run after the page loads.
  • Inline JavaScript handlers
    • Connects events directly with elements.
    • It is considered bad practice.
      • Why? Mixing JS and HTML makes code harder to read and debug.

JavaScript Examples

  • Download lec13-js-demo.html from GitHub (OIM3690/resources/templates)
  • Open the file in a web browser and interact with it.
  • Read the source code carefully.
  • Ask one question about the code.
    • It can be about anything (syntax, meaning, purpose, behavior).

JavaScript - Basic Concepts

Document Object Model (DOM)

  • The DOM is how JavaScript interacts with a webpage.
    • It represents a webpage as a tree structure that JavaScript can modify.
    • Think of it as a family tree of HTML elements.
  • See example
  • Data Types in DOM
    • Document: The entire webpage.
    • Node: Any individual part of the document (element, text, comment, etc.).
    • Element: A specific HTML tag (e.g., <p>, <div>, <button>).
    • NodeList: A collection of elements (like an array of elements).

Data Types in DOM - Document

  • The Document is the root of the DOM hierarchy, representing the entire webpage.
  • Provides methods to access elements
    document.getElementById("title"); // Finds an element by ID
    document.getElementsByTagName("p"); // Gets all <p> elements
    
  • Example:
    <h1 id="title">Hello</h1>
    <script>
      document.getElementById("title").textContent = "JavaScript Updated!";
    </script>
    

Data Types in DOM - Node

  • A Node is any object in the DOM tree (elements, attributes, text, comments).
  • Common properties:
    element.parentNode;  // Get parent node
    element.childNodes;  // Get all child nodes
    element.textContent; // Get or change text
    
  • Example:
    <p>Hello <span>World</span></p>
    <script>
      console.log(document.querySelector("p").childNodes); // Logs text + <span>
    </script>
    

Data Types in DOM - Element

  • An Element is a type of Node representing an HTML tag (e.g., <div>, <p>).
  • Common methods:
    element.setAttribute("class", "myClass"); // Add a class
    element.appendChild(newElement);          // Add a child element
    
  • Example:
    <p id="text">Hello</p>
    <script>
      document.getElementById("text").setAttribute("class", "highlight");
    </script>
    

Data Types in DOM - NodeList

  • A NodeList is a collection of Nodes, like an array.
  • Allows iterating over multiple elements:
    let items = document.querySelectorAll("li");
    items.forEach(item => console.log(item.textContent)); // Loops through list items
    
  • Example:
    <ul>
        <li>Item 1</li>
        <li>Item 2</li>
    </ul>
    <script>
        let items = document.querySelectorAll("li");
        console.log(items.length); // Outputs: 2
    </script>
    

What is an Event?

alt=""

What is an Event?

alt=""

Handling Events

  • Event Listener
    • A function that listens for a specific event (e.g., click, keydown) and runs code in response.
    • Syntax: EventTarget.addEventListener()
    • Example:
      document.querySelector("button").addEventListener("click", () => {
        alert("Button clicked!");
      });
      
  • Event Handler
    • Syntax: onevent
    • More in the next slide

Registering onevent Handlers

  • Two common ways to register event handlers:
    1. Inline Event Handler - adding an HTML attribute named on<eventtype>:
      <button onclick="alert('Clicked!')">Click me</button>
      <!-- Bad practice because it mixes JS with HTML (harder to maintain). -->
      
    2. *JavaScript Event Handler - setting the corresponding property in JS:
      document.querySelector("button").onclick = function() { 
          alert('Clicked!'); 
      }
      // Can only register one event handler per event.
      
  • Practice: modify lec13-js-demo.html, so it does not use inline event handlers.

Object Properties & Methods

  • What are objects in JavaScript?
    • In JavaScript, everything is an object (strings, arrays, DOM elements, etc.).
    • Objects have:
      • Properties: Describe characteristics (noun).
      • Methods: Perform actions (verb).

Object Properties

  • Properties describe the characteristics of an object.
    • Different types of objects have different properties.
  • Use dot notation: object.property
  • Examples:
    • document.title - the title property of a web page document
      • document.title = "New Title"; // changes the title of the page.
    • element.style.color - the color property of the element's style
      • document.querySelector("h1").style.color = "red";
    • document.querySelector("#babson").src = "new-babson-image.jpg";

Object Methods

  • Methods are functions inside objects that do something.
  • Use dot notation: object.method(arguments)
    • arguments could be empty.
  • Examples:
    • document.querySelector("#main") - Finds the first element with ID "main".
    • console.log(message)
      • Outputs message to the console.
      • This is an important way to debug and to display messages for the user.
    • element.setAttribute("class", "highlight")
      • Adds a class to an element.

Practice

Experiment with lec13-js-demo.html using what you just learned.

Questions?