Sppu Unit 2 Notes Web Technology
Sppu Unit 2 Notes Web Technology
• Node.js: Allows JavaScript to run on the server-side, enabling full-stack JavaScript development.
• React Native: Used for building native mobile applications for iOS and Android.
• Electron: Facilitates the creation of cross-platform desktop applications using web technologies.
JavaScript in Perspective
Understanding JavaScript's core characteristics is key to leveraging its full potential:
Case-Sensitivity Comments
JavaScript is case-sensitive, meaning myVariable is different • Single-line comments: Begin with //. Everything after //
from MyVariable. Pay close attention to capitalization. on that line is ignored by the interpreter.
Semicolons • Multi-line comments: Start with /* and end with
*/. They can span multiple lines and are often used
Statements are typically terminated with a semicolon (;). While for block explanations or temporarily disabling code
Automatic Semicolon Insertion (ASI) can make them optional in sections.
many cases, explicit use is highly recommended for clarity and
to prevent unexpected behavior.
Example:
// This is a single-line comment
let greeting = "Hello, World!"; // Declares a variable and assigns a string
/*This is a multi-line comment.
It demonstrates how comments can span across several lines.*/
console.log(greeting); // Prints the value to the console
Hello, World!
Variables and Data Types: Storing Information
Variables are containers for storing data values. In JavaScript, you declare them using var, let, or const,
each with distinct scoping and reassignment rules.
var let const
(Older, pre-ES6) Function-scoped. Variables declared (ES6+) Block-scoped. let allows variables to be reassigned (ES6+) Block-scoped. Variables declared with const must
with var can be redeclared and reassigned, which can but not redeclared within the same scope, offering more be initialized at declaration and cannot be reassigned. This
sometimes lead to unexpected behavior in larger predictable behavior than var. is preferred for values that should remain constant
codebases. throughout execution.
Example:
Output:
• •includes:
Plain Objects: { name: "Alice", age: 30 }
Boolean: Represents a logical entity, either true or false.
• • Arrays: Ordered collections of values. E.g., ["apple",
Undefined: Represents a variable that has been declared
but not yet assigned a value. E.g., let x; // x is "banana"]
Functions: Reusable Code Blocks // Calling the functions and logging their outputs
Functions are blocks of reusable code designed to perform a console.log("--- Function Call Outputs ---");
particular task. They can accept input (arguments) and return
output. JavaScript supports different ways to define functions: // Call greet()
const greetingMessage = greet("John");
console.log("Output of greet('John'):",
// Function declaration
greetingMessage);
function greet(name)
// Call multiply()
{
const product = multiply(5, 3);
return "Hello, " + name + "!";
console.log("Output of multiply(5, 3):", product);
}// Function expression
// Call add()
const multiply = function (a, b) {
const sum = add(10, 7);
return a * b;
console.log("Output of add(10, 7):", sum);
};
In JavaScript, almost everything can behave like an object. An object is a collection of key-value pairs (properties) and functions (methods
const person =
{ name: "Alice",
age: 30, isStudent: false,
greet: function () {
console.log("Hi, my name is " + this.name);
},
};
console.log(person.name); // Accessing a property
person.greet(); // Calling a method
Output:
Alice
Hi, my name is Alice
Arrays: Ordered Collections
Arrays are special types of objects used to store ordered collections of values. They are zero-indexed, meaning the first element is at
index 0.
Output:
Apple
4
Built-in Objects & Debuggers: Essential Tools
JavaScript provides a rich set of built-in objects that offer a wide range of functionalities, making common programming tasks much
easier. Alongside these, understanding how to use debuggers is crucial for identifying and fixing errors in your code.
debugger; // This will pause execution in developer tools if they're open debugger Statement:
return area;
}
• Console: For logging messages, inspecting variables, and running small code snippets.
• Sources Panel: Allows you to set breakpoints, step through your code line by line, inspect variable values,
and examine the call stack.
• Network Panel: To inspect network requests made by your application.
• Elements Panel: To inspect and modify the HTML and CSS of your page.
How to Use: Right-click on any web page and select "Inspect" (or F12). Navigate to the "Sources" tab to set
breakpoints and step through your code. Use console.log() for quick inspections.
The Document Object
Model (DOM):
Interacting with Web
Content
Understanding, manipulating, and enhancing web pages is crucial
for modern web development. This presentation will guide you
through the intricacies of the Document Object Model (DOM), from
its historical roots to its modern applications.
by Aditya Nandgirwar
Agenda: Navigating the DOM Landscape
1 Introduction to the DOM
Defining what the DOM is and why it's essential for web interaction.
When a web page loads, the browser parses the HTML. It creates a DOM tree in memory. JavaScript interacts with
this in-memory representation.
Why is the DOM Important?
Dynamic Pages
Enables interactive web pages. Update content without reloading. Create animations and effects.
JavaScript's Gateway
It's the primary API. JavaScript manipulates web page structure and appearance. Respond to user
actions.
Accessibility
Proper DOM manipulation enhances accessibility. Changes ARIA attributes for users with disabilities.
DOM History: The Path to Standardization
The Wild West (Mid-1990s) The Call for Standardization (Late 1990s)
Netscape Navigator and Microsoft Internet Explorer The W3C recognized the need for a common,
introduced proprietary methods for web content interoperable standard. Their goal was to create a
manipulation. These implementations were consistent set of APIs that all browsers could
incompatible, forcing developers to write browser- implement reliably.
specific code.
This was the era of "Works best in Netscape" or This effort aimed to end the browser wars and promote
"Optimized for IE." cross-browser compatibility.
DOM Levels: A Journey of Evolution
DOM Level 0 (Informal) 1
Non-standardized, browser-specific DOMs before W3C.
E.g., document.layers (Netscape 4) or document.all
(IE 4). 2 DOM Level 1 (1998)
Focused on core document structure. Defined Node,
Document, Element objects. No event handling included.
DOM Level 2 (2000) 3
Major milestone! Introduced the Event Model
(addEventListener). Added CSS styling
(getComputedStyle). Supported XML namespaces.
4 DOM Level 3 (2004)
Further refined functionality. Added document
loading/saving, validation, keyboard events. More robust
Modern DOM (Living Standard) 5 features.
Output:
Welcome
header
Using getElementById is often the quickest way to grab an element, especially for major page sections or interactive components.
Its efficiency stems from directly indexing the DOM by ID, avoiding a full tree traversal.
Selecting Elements by Class Name: Dynamic
Collections
document.getElementsByClassName() Practical Use Cases
This method returns a live HTMLCollection of all Ideal for applying styles or behavior to multiple elements
elements that share a specified class name. The "live" that serve a similar purpose, such as all form inputs,
aspect is crucial: if elements with that class are navigation links, or interactive cards. Its live nature
dynamically added or removed from the document, the means you don't need to re-query the DOM after
collection automatically updates, reflecting the current structural changes related to these classes.
state of the DOM.
Understanding the "live" nature of HTMLCollections returned by this method is key to avoiding unexpected behavior in dynamic
web applications. Always be mindful that the collection reflects the DOM's most current state.
document.getElementsByClassName('className'): This returns a live
HTMLCollection of all elements that have the specified class name. "Live"
means the collection automatically updates if elements with that class are
added or removed from the document.
Code Example:
HTML
Output:
2
(Visually: "Item 1" appears in blue)
Navigating the Document Tree:
Relationships and Traversal
Once you have a reference to a DOM node, you can traverse the document tree to access its parent, children, or siblings. This
allows for dynamic interaction with related elements without needing to re-query the entire document.
Parent Node
element.parentNode: Returns the direct parent Node of the element. This can be an Element, Document, or DocumentFragment.
Children Elements
element.children: Returns a live HTMLCollection containing only the element children (ignoring text nodes or comments).
element.firstElementChild and element.lastElementChild provide quick access to the first and last child elements, respectively
Sibling Elements
element.nextElementSibling: Returns the next sibling Element in the document tree.
JavaScript:
const child1 = document.getElementById('child1');
console.log("Parent of child1:",
child1.parentNode.id);
const parentDiv = document.getElementById('parent');
console.log("Children of parent:",
parentDiv.children.length);
console.log("First child element:",
parentDiv.firstElementChild.textContent);
Intrinsic event handling
Intrinsic event handling refers to adding event handlers directly in the HTML element's tag using event
attributes like onclick, onmouseover, etc.
Concept Description
Basic Example Intrinsic Events Event is written inside the HTML tag
<!DOCTYPE html> Handler Location Function is defined in a <script> block
<html> Common Events onclick, onmouseover, onchange, etc.
<body>
More Intrinsic Event Examples
<button onclick="showMessage()">Click Me</button>
<!-- Mouse Events -->
<p onmouseover="this.style.color='red'">Hover over me</p>
<script>
function showMessage() { <!-- Form Events -->
alert("Button was clicked!"); <input type="text" onchange="alert('Text changed!')">
}
</script> <!-- Keyboard Events -->
<input type="text" onkeydown="console.log('Key pressed')">
</body>
</html>
Concept Description
Intrinsic Events Event is written inside the HTML Tag
Handler Location Function is Defined in a <script> block
Commom Events Onclick,onmouse,onchane,etc
Modifying element style
To modify an element's style using JavaScript and the DOM, you can directly access the style property of the element. Here's how you do it:
Basic Syntax: Tip: Add multiple styles at once using
(a) setAttribute or style.cssText
element.style.property = "value";
element.setAttribute("style", "color: blue; font-weight: bold;");
<!DOCTYPE html>
<html> EXAMPLE:
<head> para.setAttribute("style", "color: blue; font-weight: bold; background-color: lightgray;");
<title>Style Change</title>
</head> (b) Using element.style.cssText = "..."
<body>
EXAMPLE:
<p id="myPara">This is a paragraph.</p> para.style.cssText = "color: green; font-style: italic; background-color: #f0f0f0;"
<button onclick="changeStyle()">Change Style</button>
<script>
function changeStyle() {
var para = document.getElementById("myPara"); Both approaches set multiple styles at once, but:
para.style.color = "red";
para.style.fontSize = "20px"; setAttribute can override existing inline styles completely.
para.style.backgroundColor = "yellow";
} cssText can also replace all inline styles, but gives slightly more direct DOM
</script> control.
</body>
</html>
The Document Tree: Visualizing the DOM
The DOM represents a document as a logical tree
structure. Every part of an HTML document is a "node"
in this tree. Nodes have parent-child and sibling
relationships.
This hierarchical structure allows developers to traverse and manipulate elements programmatically. Understanding
this tree is fundamental to effective DOM interaction.
DOM event handling
DOM event handling uses JavaScript to assign functions (event handlers) to DOM elements, separating structure (HTML) and
behavior (JavaScript) — a best practice in web development.
3 Main Ways to Handle Events in the DOM: 1. Using element.onclick (Property Method)
<script>
document.getElementById("btn").onclick = function() {
alert("Button clicked!");
};
</script>
</body>
</html>
2. Using addEventListener() (Recommended) Example: Handling Multiple Events Common Events in DOM
• You can add multiple listeners for the same event. addEventListener("click", ...): Adds a click event listener to the button.
jQuery is still used in legacy systems but is less preferred in modern single-page applications (SPAs).
Basic Example
<!DOCTYPE html>
<html>
Explanation:
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js
$(document).ready(function(){
"></script>
$("#btn").click(function(){
</head>
$("#demo").hide();
<body>
});
});
<p id="demo">Click the button to hide me!</p>
<button id="btn">Hide</button>
✅ What it means:
<script>
Line Explanation
$(document).ready(function(){
$("#btn").click(function(){
$(document).ready(...) Ensures the DOM is fully
$("#demo").hide();
loaded before running the code.
});
$("#btn") Selects the button with id="btn".
});
.click(function(){...}) Adds a click event handler to the
</script>
button.
$("#demo").hide(); Hides the paragraph with
</body>
id="demo" when the button is clicked.
</html>
AngularJS
Two-way Binding -> Syncs data between model and view automatically
SPA Friendly -> Built-in routing and controllers for single-page apps
Line-by-Line Explanation:
Example:
1. <!DOCTYPE html>
<!DOCTYPE html> Declares the document as an HTML5 page.
<html ng-app>
2. <html ng-app>
<head> ng-app is a directive that tells AngularJS:
<script 👉 "Start AngularJS here!"
4. <div ng-init="name='John'">
<div ng-init="name='John'"> ng-init initializes the AngularJS variable name with the value "John".
<p>Hello, {{name}}!</p>
So, inside Angular, we now have: name = "John"
<input type="text" ng-model="name">
</div> 5. <p>Hello, {{name}}!</p>