Web Technology Unit2
Web Technology Unit2
Web Technology
Artificial Intelligence & Data Science
Third Year (2019 Pattern)
Unit-2 (NOTES)
Unit 2: Client Side Technologies:
JavaScript and DOM
1. Introduction to JavaScript
Detailed Explanation:
Mathematical / Technical Aspect: JavaScript has a Math object with various properties
and methods for mathematical constants and functions.
Real-World Examples:
1. Form Validation: Checking if a user has entered a valid email address or filled out
all required fields before submitting a form.
2. Interactive Maps: A map that allows you to zoom in and out, drag to different
locations, or click on markers to get information.
3. Image Sliders/Carousels: A set of images on a website that automatically cycles or
can be navigated by clicking arrows.
Applications:
● Web Development: Creating interactive web pages, dynamic user interfaces, and
single-page applications (SPAs).
● Server-Side Development: Using Node.js, JavaScript can be used to build back-end
services, APIs, and microservices.
● Mobile App Development: Frameworks like React Native and NativeScript allow
developers to build cross-platform mobile applications using JavaScript.
2. JavaScript in Perspective
Detailed Explanation:
● HTML: Provides the basic structure and content of a web page (e.g., headings,
paragraphs, images).
● CSS: Styles the content, dictating how the elements look (e.g., colors, fonts, layout).
● JavaScript: Adds behavior and interactivity to the page (e.g., animations,
responding to button clicks, updating content).
● Evolution: Initially created in 1995 to add simple interactive features, its power has
grown exponentially, leading to frameworks like React, Angular, and Vue.js that
allow for complex web applications.
Mathematical / Technical Aspect: Not directly applicable to this topic, but the
perspective includes its use in modern web frameworks. For instance, the declarative
syntax of React uses JSX (a JavaScript extension) to describe the UI, which is then
dynamically updated.
Real-World Examples:
1. Google Maps: The entire user experience—dragging the map, zooming, and
clicking on pins—is powered by JavaScript, which updates the map display without
a full page reload.
2. Social Media Feeds: Infinite scrolling on platforms like Twitter or Facebook, where
new content loads automatically as you scroll down, is a classic example of
JavaScript.
3. Online Banking Dashboards: Interactive charts and graphs that display your
financial data and update in real time are built with JavaScript libraries.
Applications:
● Modern Web Applications: Building complex, feature-rich web apps that behave
like desktop software.
● Game Development: Creating browser-based games using libraries like Phaser or
Babylon.js.
● Serverless Computing: Writing functions that run on-demand on cloud platforms
like AWS Lambda or Google Cloud Functions.
Detailed Explanation:
● Basic Syntax:
○ Case-Sensitivity: JavaScript is case-sensitive (myVariable is different from
myvariable).
○ Semicolons: Semicolons (;) are used to terminate statements, though they
are often optional in modern JS due to Automatic Semicolon Insertion (ASI).
It's a best practice to use them.
○ Comments: Comments are ignored by the JS engine. Single-line comments
start with // and multi-line comments start with /* and end with */.
● Variables:
○ Declared using var, let, or const.
○ var is function-scoped and can be re-declared.
○ let is block-scoped and cannot be re-declared in the same scope.
○ const is block-scoped and cannot be reassigned after initialization.
● Data Types:
○ Primitive Types:
■ String: Textual data (e.g., "Hello World").
■ Number: Numeric data, including integers and floats (e.g., 100, 3.14).
■ Boolean: Represents true or false.
■ null: Represents the intentional absence of any object value.
■ undefined: Represents a variable that has been declared but has not yet
been assigned a value.
■ Symbol: A unique and immutable primitive value.
○ Non-Primitive (Object) Type:
■ Object: A complex data type that can store collections of data. This
includes arrays, functions, and plain objects.
● Variable Declaration:
○ let myVariable = 10;
○ const PI = 3.14159;
● Type Checking: The typeof operator can be used to check the data type of a
variable.
○ typeof "Hello" would return "string".
○ typeof 123 would return "number".
Real-World Examples:
1. User Name: Storing a user's name as a String variable (let userName = "Alice";).
2. Shopping Cart Total: Keeping track of the total cost of items as a Number variable
(let totalCost = 150.75;).
3. Login Status: Using a Boolean variable to indicate if a user is logged in or not (let
isLoggedIn = true;).
Applications:
● Data Storage: Storing and manipulating all kinds of information in a program, from
user input to configuration settings.
● Conditional Logic: Using boolean values to control the flow of a program with
if/else statements.
● Calculations: Performing mathematical operations on number variables to
calculate prices, scores, or measurements.
● Use let and const over var for better code clarity and to avoid common errors.
● const is preferred for variables that should not be reassigned.
● JavaScript is loosely typed, meaning you don't need to specify a data type when you
declare a variable.
Detailed Explanation:
● Statements:
○ Statements are typically terminated with a semicolon.
○ Examples include variable declarations, function calls, and control flow
statements like if and for loops.
○ A block of statements is enclosed in curly braces {}.
● Operators:
○ Arithmetic Operators: +, -, *, /, % (modulus), ** (exponentiation).
○ Assignment Operators: =, +=, -=, *=, /=.
○ Comparison Operators: == (equal value), === (equal value and type), !=, !==, >,
<, >=, <=.
○ Logical Operators: && (AND), || (OR), ! (NOT).
○ Unary Operators: ++ (increment), -- (decrement).
● Literals:
○ Number Literals: 100, 3.14, 0xAF (hexadecimal).
○ String Literals: "Hello World", 'JavaScript'.
○ Boolean Literals: true, false.
○ Array Literals: [1, 2, 3].
○ Object Literals: { name: "John", age: 30 }.
○ Function Literals: function() { ... }.
Real-World Examples:
1. Login Check: A statement like if (password === "secret") uses a comparison
operator (===) to check if the entered password is correct.
2. Shopping Cart Update: The total += itemPrice statement uses an assignment
operator (+=) to add the price of a new item to the total.
3. Generating a Message: Using a string literal to create a greeting: let message =
"Welcome, " + userName + "!";
Applications:
● Control Flow: Using operators and statements to make decisions in a program (e.g.,
executing different code blocks based on user input).
● Calculations and Manipulations: Performing mathematical and string operations
on data.
● Data Representation: Using literals to directly represent fixed values in the code.
● The difference between == and === is crucial: == performs type coercion, while ===
checks both value and type without coercion.
● Operators have an order of precedence that determines which operations are
performed first.
● Literals are the raw data values that you write directly into your code.
5. Functions
Detailed Explanation:
Real-World Examples:
1. Calculating a User's Age: A function calculateAge(birthYear) that takes a birth year
as a parameter and returns the user's current age.
2. Generating a Greeting: A function greet(name) that takes a name and returns a
string like "Hello, [name]!".
3. Form Submission: A function validateForm() that is called when a user clicks the
submit button to check all the fields and either submit the form or display an error
message.
Applications:
● Code Reusability: Functions allow you to write a piece of code once and use it
multiple times.
● Modularity: Breaking down a large program into smaller, manageable functions
makes the code easier to understand, debug, and maintain.
● Event Handling: Functions are used as event handlers, executing code when a
specific event (like a button click) occurs.
Definition: An object is a non-primitive data type that stores a collection of related data
and functionality. It is a container for named values, known as properties, and functions,
known as methods. An array is a special type of object used to store an ordered
collection of values, identified by a numeric index. They are the primary ways to store
complex data in JavaScript.
Detailed Explanation:
● Objects:
○ Structure: Key-value pairs enclosed in curly braces {}. The key is a string (or
Symbol), and the value can be any data type.
○ Accessing Properties: Properties can be accessed using dot notation
(object.property) or bracket notation (object['property']).
○ Methods: Functions stored as object properties.
● Arrays:
○ Structure: An ordered list of values enclosed in square brackets [].
○ Accessing Elements: Elements are accessed using a zero-based numeric
index (array[0]).
○ Methods: Arrays have many built-in methods for manipulation, such as
push(), pop(), shift(), unshift(), slice(), splice(), and forEach().
● Object Literal: const user = { name: "Alice", age: 25, isStudent: true };
● Array Literal: const numbers = [10, 20, 30];
● Accessing a property and an element: console.log(user.name); // "Alice"
console.log(numbers[1]); // 20
Real-World Examples:
1. User Profile: An object could represent a user with properties like name, email, and
profilePicture.
2. Shopping Cart: An array could store a list of product objects, where each object
has properties like id, name, and price.
3. Weekly To-Do List: An array of strings, where each string is a task for the day. For
example: let tasks = ["groceries", "laundry", "study"];.
Applications:
7. Built-in Objects
Definition: Built-in objects are objects provided by the JavaScript environment (the
browser or Node.js) that offer a set of pre-defined properties and methods to perform
common tasks. These objects are part of the core language and are globally available for
use. They provide essential functionality for working with numbers, strings, dates, and
other data types.
Detailed Explanation:
● String: An object that represents text and has methods for manipulating strings
(e.g., toUpperCase(), substring(), indexOf()).
● Number: An object wrapper for numeric values with properties like
Number.MAX_VALUE and methods for formatting numbers.
● Boolean: A wrapper object for true and false values.
● Array: Provides methods for manipulating arrays, such as push(), pop(), join(), and
map().
● Math: An object that contains mathematical constants and functions (e.g., Math.PI,
Math.random(), Math.round()).
● Date: An object used to work with dates and times, with methods to get, set, and
format dates.
● JSON: A global object that has methods for parsing (JSON.parse()) and converting
(JSON.stringify()) JavaScript objects to and from JSON (JavaScript Object Notation)
strings.
Real-World Examples:
1. Current Time Display: Using the Date object to get the current time and display it
on a web page.
2. Random Number Generation: Using Math.random() to simulate a dice roll in a
web-based game.
3. Data Persistence: Using JSON.stringify() to convert an object into a string to store
it in local storage, and JSON.parse() to convert it back when needed.
Applications:
8. JavaScript Debuggers
Definition: A JavaScript debugger is a tool that allows developers to find and fix errors
(bugs) in their code. It enables you to pause the execution of your code, examine the
values of variables, and step through the code line by line to understand its flow.
Debuggers are integrated into most modern web browsers and are an indispensable part
of the development process.
Detailed Explanation:
● Breakpoints:
○ A breakpoint is a line of code where the debugger will automatically pause
execution.
○ This allows the developer to inspect the state of the application at a specific
moment.
● Stepping:
○ Step Over: Executes the current line of code and moves to the next line. If
the current line is a function call, it executes the entire function and moves
to the next line.
○ Step Into: Executes the current line of code. If the current line is a function
call, it enters the function and pauses at the first line of the function's code.
○ Step Out: Resumes execution of the current function and pauses at the next
line after the function call.
● Call Stack: Shows the chain of function calls that led to the current point of
execution, which is useful for tracing the program's flow.
● Watch Expressions: Allows you to monitor the value of a specific variable or
expression in real time as you step through the code.
Real-World Examples:
1. Finding a Logic Error: A function is returning an incorrect value. You can set a
breakpoint inside the function to see the value of each variable at every step and
find where the calculation goes wrong.
2. Troubleshooting UI Bugs: An element is not showing up as expected. You can use
the debugger to check if the JavaScript code is correctly setting the element's
properties or if an error is preventing the code from executing.
3. Asynchronous Code: Debugging a function that fetches data from an API to ensure
the data is received correctly before the rest of the program tries to use it.
Applications:
● Error Correction: The primary purpose of a debugger is to identify and fix bugs.
● Learning and Understanding: It is an excellent tool for understanding how a
complex piece of code works by observing its execution step-by-step.
● Performance Analysis: Some debuggers include tools for profiling code to identify
performance bottlenecks.
● The browser's developer tools (F12 or Cmd+Option+I) are the most common way to
access a debugger.
● Learning how to use a debugger effectively is a crucial skill for any developer.
● It's a more powerful and efficient way to find errors than using console.log()
statements.
Definition: The Document Object Model (DOM) is a programming interface for web
documents. It represents the structure of an HTML or XML document as a tree of
objects, where each object corresponds to a part of the document, such as an element,
attribute, or text. The DOM allows JavaScript to access, manipulate, and modify the
content, structure, and style of a web page dynamically.
Detailed Explanation:
● Tree Structure: The DOM is organized like a family tree, starting with a root
Document node, which has child nodes like <html>, which in turn has children like
<head> and <body>.
● Nodes: Every item in the document—elements, attributes, text—is a node. The most
common type of node is the element node.
● API (Application Programming Interface): The DOM provides a set of methods and
properties that JavaScript can use to interact with the document.
● Dynamic Manipulation: With the DOM, you can create new HTML elements,
change the content of existing ones, remove elements, and modify styles and
attributes.
Real-World Examples:
1. Changing the text on a button: A button that says "Click Me" can be changed to
"Clicked!" after a user presses it.
2. Dynamically adding a list item: Clicking an "Add Item" button creates a new list
item (<li>) and appends it to an unordered list (<ul>).
3. Toggling a "dark mode": A button click changes the <body> element's class, and
CSS rules then apply a dark color scheme to the entire page.
Applications:
● Dynamic Content Updates: Updating parts of a web page without a full reload, a
cornerstone of modern web applications.
● Event Handling: Attaching event listeners to elements to respond to user actions.
● UI/UX Enhancements: Creating interactive user interfaces, animations, and
transitions.
● The DOM is not JavaScript itself, but an API that JavaScript uses.
● The DOM represents the page in a logical tree structure.
● All web page content, from tags to text, is accessible as a node in the DOM.
10. DOM History and Levels
Definition: The DOM's history began with early web browsers that implemented their
own versions of a Document Object Model, leading to compatibility issues. To
standardize this, the World Wide Web Consortium (W3C) developed different
specifications, known as "levels," to provide a consistent and cross-browser way to
interact with web documents. These levels defined a series of features and functionalities
that modern browsers now widely support.
Detailed Explanation:
Real-World Examples:
1. Cross-browser compatibility: A developer writing code today doesn't have to
worry about whether addEventListener will work in different browsers because it's
a part of the standardized DOM Level 2.
2. Event Bubbling and Capturing: These concepts, introduced in DOM Level 2, allow
events to propagate through the DOM tree, which is a key feature of modern event
handling.
3. Accessing CSS: Modifying an element's style using element.style.color = "red" is a
feature standardized in DOM Level 2.
Applications:
Definition: Intrinsic event handling, also known as inline event handling, involves
specifying a JavaScript function to be executed directly within an HTML element's
attribute. The event handler is declared using an attribute like onclick, onmouseover, or
onsubmit, which maps to a specific user action or event. This approach is simple for
small, self-contained interactions but is generally considered outdated for complex
applications.
Detailed Explanation:
● Inline HTML Attributes: The event handler code is written directly inside an
HTML tag.
○ Example: <button onclick="alert('Hello!');">Click Me</button>
● Direct Function Call: The attribute value is a JavaScript statement, often a function
call.
● Limited Scope: The code is tied to a specific HTML element, making it difficult to
manage and reuse.
● Mixing Concerns: It violates the principle of "separation of concerns" by mixing
HTML (structure) with JavaScript (behavior).
Real-World Examples:
1. Simple Alert: An <a href="#" onclick="alert('You clicked the link');"> link that
displays a pop-up message when clicked.
2. Image Change on Hover: An <img onmouseover="this.src='new_image.jpg'"
onmouseout="this.src='old_image.jpg'"> tag that changes the image source when
the mouse hovers over it.
3. Form Submission: An <form onsubmit="return validateForm()"> that calls a
validateForm function before submitting. If the function returns false, the
submission is prevented.
Applications:
● Quick Prototypes: Useful for very simple, one-off interactions where speed of
development is more important than long-term maintainability.
● Small Scripts: For very small, non-critical scripts on a static web page.
● Backward Compatibility: Still found in older codebases or when a developer needs
to support very old browsers.
Important Notes / Key Takeaways:
Detailed Explanation:
● Direct Style Access: You can access and modify an element's inline styles using the
style property.
○ Example: element.style.color = "red";
● Camel Case Naming: CSS properties with hyphens (e.g., font-size) are converted to
camel case in JavaScript (e.g., fontSize).
● Changing Classes: A more powerful and preferred method is to add, remove, or
toggle CSS classes on an element using element.classList.
○ This approach separates presentation (CSS) from behavior (JavaScript) and is
easier to maintain.
○ Example: element.classList.add("highlight");
● Inline vs. Class-based: Modifying styles directly changes the inline style attribute,
which has high specificity. Using classes is better because it leverages the power of
CSS stylesheets for consistent styling.
Real-World Examples:
1. Highlighting a selected item: Clicking on a list item adds a selected class, which
changes its background color to highlight it.
2. Animating an element: Using JavaScript to incrementally change an element's left
or top style property to create a simple animation.
3. Responsive Design: Dynamically changing an element's display property from
block to none to show or hide a mobile menu.
Applications:
● Interactive UI: Creating dynamic user interfaces with visual feedback, such as
button hover effects or form field validation styles.
● Animations and Transitions: Implementing client-side animations without relying
on complex CSS transitions.
● Theming: Allowing users to switch between different color themes (e.g., light
mode/dark mode) by changing a class on the <body> element.
● While direct style manipulation is possible, it's generally best to use classList to
manage CSS classes.
● classList keeps your JavaScript code clean and your styles in your CSS file.
● Remember to use camel case for CSS property names in JavaScript.
● Root Node: The document object is the root of the tree. The <html> element is its
single child.
● Parent-Child Relationships: An element that contains other elements is called a
parent node. The contained elements are its children.
● Sibling Relationships: Nodes that share the same parent are called siblings.
● Traversing the Tree: The DOM provides properties to navigate the tree:
○ parentNode: Gets the parent node.
○ childNodes: Returns a collection of all child nodes.
○ firstChild, lastChild: Accesses the first and last child nodes.
○ nextSibling, previousSibling: Accesses the next and previous sibling nodes.
○ children, firstElementChild, etc., are newer properties that only return
element nodes, which is often more useful.
Real-World Examples:
1. Event delegation: Instead of attaching an event listener to every list item in a large
list, you can attach a single listener to the parent <ul>. When a list item is clicked,
the event "bubbles up" to the parent, and you can determine which child was
clicked by checking event.target.
2. Collapsible Menu: Clicking a header element finds its next sibling (a hidden <div>)
and toggles its visibility.
3. Form Validation: A function iterates through the children of a <form> element to
find all the <input> fields and validate them.
Applications:
Definition: DOM event handling is the mechanism by which JavaScript listens for and
responds to events that occur on a web page. An event is an action or occurrence that
happens in the browser, such as a user clicking a button, a page loading, or a key being
pressed. Event handling involves registering a function, called an event listener, to be
executed whenever a specific event is triggered on an element.
Detailed Explanation:
● Events: A variety of events exist, including click, mouseover, keydown, load, submit,
change, etc.
● addEventListener():
○ This is the modern, recommended method for event handling.
○ Syntax: element.addEventListener(event, handler, useCapture);
○ event: The event name as a string (e.g., 'click').
○ handler: The function to be executed when the event occurs.
○ useCapture: An optional boolean for event bubbling/capturing.
● Event Object: When an event fires, the event listener function receives an event
object as an argument. This object contains useful information about the event,
such as the target element (event.target), mouse coordinates, or the key pressed.
● Separation of Concerns: Using addEventListener keeps the JavaScript logic
separate from the HTML, making the code cleaner and more maintainable.
Mathematical / Technical Aspect:
Real-World Examples:
Applications:
15. jQuery
Definition: jQuery is a fast, small, and feature-rich JavaScript library. It simplifies things
like HTML document traversal and manipulation, event handling, animation, and Ajax
interactions for rapid web development. Its purpose is to make it much easier to use
JavaScript on your website by providing a simple, cross-browser compatible API that
abstracts away many of the complexities and inconsistencies of the early DOM.
Detailed Explanation:
● Selectors: jQuery uses a CSS-like selector engine to easily find and select elements
in the DOM.
○ Example: $('.my-class') selects all elements with the class "my-class".
● DOM Manipulation: Provides a much more concise syntax for manipulating the
DOM.
○ Example: $('.my-class').html('New Content');
● Event Handling: Simplifies event handling and makes it easier to work with.
○ Example: $('#my-button').click(function() { ... });
● Ajax: Provides easy-to-use methods for making asynchronous requests to a server.
● Chaining: jQuery methods can be "chained" together, allowing multiple operations
to be performed on the same set of elements in a single line of code.
Real-World Examples:
1. Image Gallery: Using jQuery to show and hide full-sized images and add
animations with minimal code.
2. Accordion Menu: Creating a collapsible menu where clicking on a header animates
the opening and closing of its corresponding content panel.
3. Contact Form Submission: Using jQuery's $.ajax() to submit form data to a server
without a page reload.
Applications:
● While still widely used, the rise of modern JavaScript and built-in browser APIs has
reduced the need for jQuery in new projects.
● Many of jQuery's features are now part of the standard JavaScript language.
● It is still a valuable tool for working with legacy codebases or for projects where its
simplicity and extensive plugin ecosystem are a benefit.
Detailed Explanation:
● MVC Architecture: It separates the application into three main components: Model
(data), View (HTML), and Controller (logic).
● Two-Way Data Binding: A core feature where changes in the user interface
automatically update the application's data model, and vice versa, without the need
for manual DOM manipulation.
● Directives: Special attributes in HTML that tell AngularJS to do something, such as
ng-app, ng-model, and ng-repeat. These extend HTML's functionality.
● Dependency Injection: A software design pattern that allows components to
receive their dependencies (services, other components) from an external source
rather than creating them themselves, which makes the code more modular and
testable.
● Components: Reusable UI components that encapsulate a piece of the application's
functionality.
Real-World Examples:
1. Google Flights: A complex single-page application that uses AngularJS to manage
dynamic search results, filters, and flight selection.
2. YouTube on PlayStation 3: The user interface for the YouTube application was built
with AngularJS.
3. Online E-commerce Dashboards: A dashboard that displays real-time sales data
and other metrics, with charts and graphs updating automatically.
Applications:
● Single-Page Applications (SPAs): Building complex web apps that feel like native
desktop applications.
● Enterprise-Level Applications: Providing a structured and maintainable
framework for large-scale projects.
● Interactive Forms: Creating complex forms with dynamic validation and
conditional fields.
● AngularJS (version 1.x) is the original framework. The newer framework, simply
called Angular (version 2 and above), is a complete rewrite and is not backward
compatible.
● AngularJS is known for its "opinionated" structure, which provides a clear path for
development but can be restrictive.
● It pioneered many concepts like two-way data binding and directives that are now
common in other frameworks.
Summary Table
Main Topic Brief Definition 3 Real-World Example
Name
Basic Syntax, The foundational rules for writing JavaScript 1. Storing a user's name as a String.
Variables & code. This includes case-sensitivity and <br>2. Tracking a shopping cart's total as a
Data Types semicolons. Variables are named containers Number. <br>3. Using a Boolean to check
for data, and data types classify what kind of a user's login status.
data they hold (e.g., String, Number,
Boolean).
Functions A reusable block of code that performs a 1. A function to calculate a user's age
specific task. Functions can take input based on their birth year. <br>2. A function
parameters, execute a series of statements, that generates a personalized greeting
and return a value, making them essential message. <br>3. A function that validates
for organizing code and promoting all fields of a form before submission.
reusability.
Objects and Non-primitive data types used to store 1. An object representing a user with name
Arrays complex data. An object stores data in and email properties. <br>2. An array
unordered key-value pairs, while an array storing a list of products in a shopping cart.
stores an ordered list of values accessed by <br>3. An array of strings representing a
a numeric index. weekly to-do list.
DOM: Intro to A programming interface that represents a 1. Changing the text on a button after it's
Document web document as a tree of objects. It allows clicked. <br>2. Dynamically adding new list
Object Model JavaScript to dynamically access, items to a list. <br>3. Toggling a "dark
manipulate, and modify the content, mode" theme for a website.
structure, and style of a web page after it
has loaded in the browser.
DOM Event The mechanism for responding to user 1. A click event on a button to submit a
Handling actions and other occurrences on a web form. <br>2. A mouseover event to
page. It involves attaching an event listener display a pop-up with more information.
function to an element, which is executed <br>3. A keydown event listener to enable
when a specific event like a click or keyboard shortcuts.
mouseover is triggered.
jQuery A popular JavaScript library that simplifies 1. Creating a photo gallery with animated
common tasks like DOM manipulation, transitions. <br>2. Building a collapsible
event handling, and Ajax. It provides a accordion menu. <br>3. Submitting a form
simple, cross-browser compatible API that asynchronously without a page reload.
allows developers to write less code for
more functionality.
Overview of An early front-end framework for building 1. The dashboard of an online banking
AngularJS single-page applications, known for its application. <br>2. A complex single-page
two-way data binding and application like Google Flights. <br>3. An
Model-View-Controller (MVC) architecture. It e-commerce site with dynamic product
extended HTML with special directives to filtering.
create dynamic and structured web
applications.