π Lecture 12 β Some Useful Style Sheets Properties
π Overview: This lecture introduces positioning properties in CSS, including absolute, relative, and static positioning, along with z-index for three-dimensional layering. It also provides an introduction to JavaScript, covering variables, data types, event handlers, and object manipulation for creating dynamic and interactive web pages.
ποΈ Topics Covered
The lecture begins with practical examples of CSS positioning using absolute, relative, and static values, then moves to three-dimensional positioning with the z-index property. The second half introduces JavaScript fundamentals: variables, data types, event handlers, and how to change images dynamically using mouse events, concluding with a brief note on objects.
π Lecture Summary
Example position style
The lecture demonstrates CSS positioning using the position property. With position: absolute, elements are placed precisely using left and top coordinates relative to their nearest positioned ancestor. With position: static (the default), elements flow normally in the document, and left/top values are ignored. With position: relative, the element is shifted from its normal position.
π Definition β position: absolute: Positions an element precisely at specified coordinates relative to the nearest positioned ancestor (or the initial containing block if none). It removes the element from the normal document flow.
π Formula: position: absolute; left: Xpx; top: Ypx β Places the element at X pixels from the left edge and Y pixels from the top edge of the containing block.
π Example: In the code, <DIV STYLE="position: absolute; left: 700px; top: 200px">Books Section</DIV> places the text "Books Section" 700 pixels from the left and 200 pixels from the top. In the second example, <p STYLE="position: relative; left: 200px; top:5px"> shifts the paragraph 200px right and 5px down from its normal position.
Positioning in the 3rd dimension
The CSS property z-index controls how elements overlap in the third dimension (depth). Elements with a higher z-index value appear on top of those with lower values. This is useful for layering text over images or creating overlapping visual effects.
π Definition β z-index: A CSS property that specifies the stack order of positioned elements. Elements with a higher z-index value appear in front of elements with lower values. Only works on positioned elements (absolute, relative, fixed, or sticky).
π Example: The code shows an image (image2.gif) with z-index: 0 and a <DIV> element with z-index: 1 positioned at left: 10px; top: 60px. Because the div has a higher z-index (1), the text "This text appears on top of the image." displays over the image. π‘ Why this matters: z-index allows you to control visual layering, essential for creating complex layouts like dropdown menus, modals, and overlays.
Introduction to JavaScript
JavaScript is a scripting language used primarily for client-side web development to create dynamic, interactive web pages. It is distinct from Java despite the similar name.
π Definition β Variable: A named storage location in computer memory that holds a value that can be accessed and changed. For example, Var i=3; creates a variable named i storing the value 3 at a specific memory address.
Rules for variables: Variable names can begin with a letter (A-Z, a-z), underscore (_), or dollar sign ($). Subsequent characters can include digits (0-9). JavaScript is case-sensitive, meaning money, Money, and mONEY are different variables. Variables do not require explicit data type declaration in JavaScript.
General data types
JavaScript has several data types, but the lecture notes that "you don't need to define the variable with the data type." The general data types discussed include:
- Integer: Whole numbers like 78, 98
- Float: Decimal fractions like 8.9, 6.6
- Char: Single characters like 'A', '5'
- String: Sequences of characters like "hello"
- Boolean: True or false values
The lecture notes that JavaScript's specific data types are: Number, Boolean, String, Null, and Undefined. π‘ Why this matters: Understanding data types helps you know how to use variables correctly and what operations are valid.
Event handler
Event handlers are JavaScript keywords that respond to user actions (events) on an HTML page. Events occur when a user clicks, moves the mouse, submits a form, etc. Common event handlers include:
onclick: When an element is clickedonmouseover: When mouse moves over an elementonmouseout: When mouse moves away from an elementonload: When page finishes loadingonsubmit: When a form is submittedonfocus: When an element gains focusonblur: When an element loses focusonchange: When a form element changes
Changing images using event handlers
JavaScript can dynamically change images using event handlers like onmouseover and onmouseout. The lecture provides two examples:
Example 1 (without hyperlink):
<IMG SRC=contents.gif WIDTH=170 HEIGHT=50 BORDER=0 NAME=picture
onmouseover="picture.src='search.gif';picture.width=250; picture.height=100"
onmouseout="picture.src='contents.gif';picture.width=170; picture.height=50">
When the mouse moves over the image, it changes to 'search.gif' and resizes to 250x100 pixels. When the mouse leaves, it reverts to 'contents.gif' at 170x50 pixels.
Example 2 (with hyperlink):
<A href=image2.gif onmouseover="picture.src='search.gif';picture.width=250; picture.height=100"
onmouseout="picture.src='contents.gif';picture.width=170; picture.height=50">
<IMG SRC=contents.gif WIDTH=170 HEIGHT=50 BORDER=0 NAME=picture></A>
By wrapping the image in an <A> tag, the changed image (search.gif) becomes clickable and opens 'image2.gif' when clicked.
Objects
In programming, an object is a collection of properties (attributes) and functions (methods) that belong together. JavaScript provides predefined objects that are ready to use, but custom objects can also be created in object-oriented languages.
π Definition β Object: A programming construct that bundles together properties (data) and methods (functions) that operate on that data. In JavaScript, objects can be built-in (like document, window) or user-defined.
β Key Takeaways
CSS positioning (absolute, relative, static) controls element placement on the page, with absolute removing elements from normal flow and relative shifting them. The z-index property manages which elements appear on top when they overlap. JavaScript variables are case-sensitive and don't require type declaration, with data types including Number, Boolean, String, Null, and Undefined. Event handlers like onmouseover and onmouseout enable dynamic image swapping and interactive effects without page reload. Understanding these concepts is crucial for creating visually layered, interactive web pages that respond to user actions.
π§ Quick Revision Questions
- What is the difference between
position: absoluteandposition: relativein CSS? - How does the
z-indexproperty affect overlapping elements, and what must be true for it to work? - What are the rules for naming variables in JavaScript, and why is case-sensitive important?
- Name four common event handlers and describe the user action that triggers each one.
- In the image-swapping example, what happens when the mouse moves over the image, and how does wrapping it in an
<A>tag change the behavior?
π Lecture 13 β Java Scripting
π Overview: This lecture introduces JavaScript as a scripting language embedded in HTML to create interactive web pages. It covers basic JavaScript syntax, embedding scripts in HTML, browser objects, operators, functions, and practical examples including alert boxes, writing to pages, and building a simple calculator.
ποΈ Topics Covered
The lecture covers embedding JavaScript in HTML using script tags, the alert() function for popup messages, the document.write() method for writing content to web pages, browser objects (window and document), JavaScript operators (mathematical, logical, comparison), defining variables and functions, and creating an interactive calculator with event handlers that performs addition and subtraction displaying results either in alert boxes or text boxes.
π Lecture Summary
Java script examples
JavaScript instructions are embedded in HTML code using <SCRIPT> and </SCRIPT> tags with the attribute LANGUAGE="JavaScript" TYPE="text/javascript". The lecture demonstrates a simple example where an alert box appears when the page loads.
π Definition β alert(): A function/method of the predefined browser window object used to create popup messages on the window.
π Example:
<SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">
<!--
alert("Thank you for visiting my web site!")
//-->
</SCRIPT>
When the page loads, a popup appears displaying "Thank you for visiting my web site!" as shown in Fig. 1. The // is used for comments, and old browsers that don't support JavaScript treat the script content as comments.
Writing on the page
The document.write() method is used to write text directly onto the web page. The document is a browser object, and write is its function.
π Definition β document.write(): A method of the browser document object used to write text or HTML content onto the web page.
π Example:
<SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">
<!--
document.write("Hello! Thank you for visiting my web site.")
//-->
</SCRIPT>
When the page loads, the text "Hello! Thank you for visiting my web site." appears on the page (as shown in Fig. 2). Browser objects are loaded by a JavaScript-capable browser to provide access to the web page and its HTML elements, allowing interaction and updates.
Operators in java script
Three categories of operators are covered:
Mathematical operators:
+β Addition-β Subtraction*β Multiplication/β Division%β Modulus (calculates remainder)++β Increment--β Decrement
Logical operators:
&&β Logical AND||β Logical OR!β Logical NOT
Comparison operators:
==β Equal!=β Not equal<β Less than<=β Less than or equal>β Greater than>=β Greater than or equal
Functions in javascript
Variables in JavaScript are defined using the keyword var, and functions using the keyword function. A function definition follows this format:
function myfunction() {
// some code
}
Here, myfunction is the name of the function.
Creating a calculator in JavaScript
The lecture demonstrates building a simple calculator with two functions: Addit() and minus(). The event handler onclick is used in HTML button elements to trigger the appropriate function when clicked.
π Definition β parseFloat(): A JavaScript function that converts a string into a floating-point number, used for numeric calculations.
π Example (alert box version):
function Addit() {
var num1 = document.Calform.One.value;
var num2 = document.Calform.Two.value;
alert(parseFloat(num1) + parseFloat(num2));
}
The HTML form includes two text input fields named "One" and "Two" for entering numbers, and two buttons: "Add Them!!" (calls Addit()) and "Subtract Them!!" (calls minus()). When the user enters 3 in the first box and 9 in the second and clicks "Add Them!!", an alert box displays "12" (Fig. 3). Clicking "Subtract Them!!" displays "-6" (Fig. 4).
π Example (text box version):
To display the result in a text box instead of an alert box, the code changes the document.Calform.result.value property directly:
function Addit() {
var num1 = document.Calform.One.value;
var num2 = document.Calform.Two.value;
document.Calform.result.value = parseFloat(num1) + parseFloat(num2);
}
The HTML adds a third text input named "result" with the Disabled attribute so users cannot type in it. When the user enters 125 and 66 and clicks "Add Them!!", the result 191 appears in the result text box (Fig. 5). The // comments out the old alert code.
π‘ Why this matters: Understanding how to use event handlers like onclick to trigger JavaScript functions enables creating interactive web forms that respond to user input without page reloads.
β Key Takeaways
You must remember that JavaScript code is embedded in HTML using <SCRIPT> tags and can manipulate web pages through browser objects like window (for alert boxes) and document (for writing content or accessing form elements). The alert() function creates popup messages, while document.write() writes directly to the page. JavaScript has mathematical, logical, and comparison operators, and functions are defined with the function keyword. Event handlers like onclick link HTML elements to JavaScript functions. The parseFloat() function converts string input to numbers for calculations, and form elements are accessed using the dot notation structure document.FormName.ElementName.value.
π§ Quick Revision Questions
- What are the two browser objects demonstrated in this lecture, and what functions are associated with each?
- How do you embed JavaScript code within an HTML page, and why is
//used in the script tag? - Write the JavaScript code to access the value entered in a text input named "age" within a form named "myForm".
- What is the purpose of the
parseFloat()function, and why is it necessary when performing calculations with form input values? - How does the
onclickevent handler work to trigger JavaScript functions when a button is clicked?
π Lecture 14 β JAVA SCRIPTING (CONTINUED....)
π Overview: This lecture continues the study of JavaScript by demonstrating how to display arithmetic results on a web page using
document.write()andalert()functions. It also introduces conditional execution withifstatements, looping withforloops, and several predefined JavaScript objects like Global, Array, and Math, along with practical examples including a drop-down list of links.
ποΈ Topics Covered
The lecture covers displaying addition and subtraction results using document.write(), creating a multiply and divide calculator using alert(), building a drop-down list of links with the onchange event handler, using if statements for conditional subtraction, implementing for loops to generate dynamic HTML headings, and exploring predefined JavaScript objects such as Global, Array, and Math with code examples.
π Lecture Summary
Displaying Results with document.write()
We can get the result of addition or subtraction written on a page using the write function of the document object. The code uses document.write() to concatenate text strings (in double quotes) with arithmetic results using the + sign. The parseFloat() function (a method of the predefined Global object) converts text input to floating-point numbers for calculation.
π Definition β parseFloat(): A function that parses a string argument and returns a floating-point number.
π Formula: document.write("text" + (parseFloat(num1) + parseFloat(num2))) β Writes text followed by the arithmetic result on the web page.
π Example: When a user types 3 and 9 in the text boxes and clicks "Add Them!!", the result 12 is written on the page. Clicking "Subtract Them!!" writes -6.
Multiply and Divide Calculator
This example uses the alert() function to display results in a pop-up dialog box instead of writing on the page. The code defines two functions: Multiplyit() and Divideit(), each using parseFloat() to convert input values and then applying multiplication (*) or division (/) operators.
π Definition β alert(): A JavaScript function that displays a dialog box with a specified message and an OK button.
π Formula: alert(parseFloat(num1) * parseFloat(num2)) β Shows the multiplication result in a pop-up.
π Example: Entering 24 and 4, then clicking "Multiply" shows 96 in an alert box; clicking "Divide" shows 6.
π‘ Why this matters: alert() is useful for immediate feedback without modifying the page content, while document.write() overwrites the entire page content.
Example - A Drop-Down List of Links
This example creates a navigation menu using a drop-down list (select element) with the onchange event handler. When a user selects an option, the GoToIt(list) function executes. The keyword this passes the select element's information to the function's argument list. The selected option's value is assigned to variable selection, and the location.href = selection changes the browser's current page to the selected URL. Location is another predefined browser object.
π Definition β onchange: An event handler that triggers when the value of an element changes (e.g., when a user selects a different option from a drop-down list).
π Definition β this: A keyword that refers to the current HTML element (in this case, the select element).
π Example: Selecting "Calculator" from the list navigates to "calculator.htm". The default option "Select a page previously done --->" has value "None", which is ignored by the if condition.
Example - If Statement
The IF statement is used to alter the course of code execution depending on a condition. The code checks if the first number is less than the second number. If true, it displays "negative" using alert(); otherwise, it displays the subtraction result.
π Definition β IF statement: A conditional statement that executes code blocks based on whether a condition evaluates to true or false.
π Syntax: if(condition) { statements } else { statements }
π Example: With first number 3 and second number 9, the condition parseFloat(3)<parseFloat(9) is true, so "negative" is displayed. With first number 9 and second number 3, the condition is false, so the subtraction result 6 is displayed.
For LOOP
When we want some action to take place repeatedly until a particular condition is met, we can apply a for loop. The general format is: for(initializationStatement; condition; updateStatement) { statements }. The code executes repeatedly while the condition remains true.
π Definition β for loop: A control flow statement that allows code to be executed repeatedly based on a given boolean condition.
π Formula: for(i=1; i<7; i++) β Initializes i to 1, runs while i is less than 7, and increments i by 1 after each iteration.
π Example: The code for(i=1;i<7;i++) document.write("<H"+i+">Hello "+i+"!!</H"+i+">"); generates six different heading levels (H1 through H6), each displaying "Hello [number]!!".
Some predefined JavaScript objects
A list of some commonly used predefined JavaScript objects includes Global, Array, String, Math, and Date.
The Global object has globally-accessible variables/properties and functions. Netscape Navigator and Internet Explorer implement it but don't allow explicit creation. Its properties and methods are referenced directly. NaN (Not a Number) is one of its properties. parseFloat(string) is a method of the Global Object. Properties do not have parentheses following their names, while functions do. Arguments are the information contained in the parentheses of a function.
The Array object has properties and functions. Length is an important property that identifies the array's size. Its methods include toString(), reverse(), sort(), and join().
π Definition β Array: An object that stores multiple values in a single variable, with each value accessible by an index number.
π Example: myArray=[0,1,2,3,4,5,6,7,8,9,10]; creates an array. myArray[0] returns 0. myArray.toString() returns "0,1,2,3,4,5,6,7,8,9,10". myArray.join(':') returns "0:1:2:3:4:5:6:7:8:9:10". myArray.reverse() returns "10,9,8,7,6,5,4,3,2,1,0". myArray.sort() returns "0,1,10,2,3,4,5,6,7,8,9" (lexicographic sort).
The Math object provides a standard library of mathematical constants and functions.
π Definition β Math object: A predefined JavaScript object with mathematical constants and methods.
π Example: Math.PI returns 3.141592653589793. Math.LN2 returns 0.6931471805599453. Math.sin(90) returns 0.8939966636005579. Math.random() returns a random number between 0 and 1 (e.g., 0.3228030884336356). Math.pow(2,3) returns 8. Math.min(123,133) returns 123.
β Key Takeaways
You must remember how to use document.write() and alert() for displaying output, and understand the difference between them β document.write() overwrites the page while alert() creates a pop-up dialog. The if statement is essential for conditional logic, and the for loop is crucial for repetitive tasks. Predefined JavaScript objects like Global, Array, and Math provide built-in functions and properties that simplify coding β particularly parseFloat() for number conversion, array methods like toString(), reverse(), and sort(), and Math methods like random(), pow(), and min(). Finally, event handlers like onchange and the this keyword are important for creating interactive web elements like navigation menus.
π§ Quick Revision Questions
- What is the difference between
document.write()andalert()when displaying results in JavaScript? - In the drop-down links example, what does the keyword
thisrefer to and how is it passed to the GoToIt() function? - Write the general syntax of a
forloop and explain its three components. - What does
parseFloat()do and which JavaScript object does it belong to? - How does the
sort()method work on an array of numbers, and what does the output ofmyArray.sort()look like for the array [0,1,2,3,4,5,6,7,8,9,10]?
π Lecture 15 β JAVA SCRIPTING (CONTINUED....)
π Overview: This lecture continues the exploration of JavaScript by demonstrating how to work with the Date object to display current date and time, and the String object with its various methods. It then applies JavaScript for client-side form validation, showing how to check user input for required fields, length constraints, pattern checks, and password confirmation before form submission, which improves data quality and user experience.
ποΈ Topics Covered
The lecture covers the Date object with examples showing how to display current date/time using the constructor Date() and how to create an instance to get user-friendly formatted dates using methods like getDay(), getMonth(), getYear(), getHours(), and getMinutes(). It then introduces the String object with examples of methods charAt(), substring(), toLowerCase(), toUpperCase(), and split(). Finally, it demonstrates using JavaScript for client-side form validation with a registration form example that checks empty fields, length constraints, special characters, and password matching.
π Lecture Summary
Example - Date object
This section shows a simple example using the Date() constructor directly within document.write() to display the current system date and time. The code <SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript"> document.write(βWelcome! you are visiting my web site on " + Date()) </SCRIPT> produces output like "Welcome! you are visiting my web site on Mon Apr 10 2025...". Here, Date() is the constructor of the date object which provides the current date of the system.
π Definition β Constructor: The initializing function used to create an instance/copy of an object. It is named after the object whose constructor it is.
π Formula: new Date() β Creates a new instance (copy) of the Date object containing the current date and time.
π Example: d = new Date() creates an instance d of the Date object, then methods like d.getDay() (returns 0-6 for Sunday-Saturday), d.getMonth() (0-11), d.getYear(), d.getHours(), and d.getMinutes() can be called.
Getting date and time in a user friendly format
To get the date/time in a different format, an instance of the date object is created. In the example, d is such an instance created using new Date(). The code then uses if statements to convert numeric day values (0-6) to day names (Sunday-Saturday), numeric month values (0-11) to month names (January-December), and handles year formatting with conditional logic for years before vs. after 2000. For time, it gets hours and minutes, formats minutes with leading zero if less than 10, and customizes greeting messages ("Good morning!", "Good afternoon!", "Good evening!") based on the hour value using multiple if-else if-else statements. The result displays a complete sentence like "Good afternoon! It's Saturday, April 10, 2025 at 2:30 PM".
π‘ Why this matters: This demonstrates how to convert raw numeric date/time values from the Date object into a human-readable, user-friendly string with customized greetings, which is commonly used on websites for personalized welcome messages.
Example - String object
This example creates str as an instance of the String object using new String("This is a test of javascript string methods") and myArray as an instance of the Array object with size 10 (though size is dynamically adjusted by split()). The charAt() method of the string object returns the character at a specified index β charAt(3) returns the character at index 3 (0-based indexing). Other methods demonstrated include: substring(20,25) extracts characters from index 20 to 25 (not including 25), toLowerCase() converts entire string to lowercase, toUpperCase() converts to uppercase, and split(' ') splits the string on blank spaces into an array, assigning each part as an array element (e.g., myArray[0] becomes "This", myArray[1] becomes "is").
π Definition β charAt(index): A method of the String object that returns the character at the specified index (0-based) within the string.
π Formula: string.split(separator) β Splits a string into an array of substrings using the specified separator character.
π Example: str="This is a test"; myArray=str.split(' '); results in myArray[0]="This", myArray[1]="is", myArray[2]="a", myArray[3]="test".
Using java script for applying for checks in a registration form
JavaScript can be used for applying different checks on a web form including pattern checking. The example defines a function checkValues() that is called when the form is submitted (via onSubmit="return checkValues()"). The function retrieves form field values using document.regForm.fieldName.value. It performs several validations: first checks if Userlogin, userAddress, or Name fields are empty (length == 0) and displays an alert "Please fill in all values". Then it checks if Userlogin length is within 3-15 characters (using variables minLength=3 and maxLength=15) and displays an alert if violated. Similarly, it checks UserPassword length within 3-15 characters. It also checks for invalid characters in Userlogin using a loop checking each character for commas or semicolons using charAt(i). Finally, it checks if UserPassword matches conPassword (confirm password) and displays "Passwords do not match" if different. If any check fails, the function returns false, preventing form submission to the server side (regcheck.asp). Only if all checks pass does it return true, allowing data to be sent to the server.
π‘ Why this matters: Client-side validation using JavaScript improves user experience by providing immediate feedback without server round-trips, reduces server load, and helps ensure data quality before submission. However, server-side validation should always complement client-side validation for security.
β Key Takeaways
The Date object provides both a simple constructor Date() and a more flexible instance-based approach using new Date() to access individual components like day, month, year, hours, and minutes through methods such as getDay(), getMonth(), getYear(), getHours(), and getMinutes(). The String object offers powerful methods like charAt(), substring(), toLowerCase(), toUpperCase(), and split() for string manipulation and parsing. JavaScript form validation is implemented by defining a function that checks form field values before submission, using the onSubmit event handler to call this function, and returning false to prevent submission when validation fails. Common validation checks include empty fields, length constraints, pattern/character checks, and password confirmation. Remember that client-side validation enhances user experience but is not a substitute for server-side validation, as JavaScript can be disabled or bypassed.
π§ Quick Revision Questions
- What is the difference between using
Date()directly and creating an instance withnew Date()? - What values does
d.getDay()return (range and meaning), and how would you convert it to a day name? - What does the
split(' ')method do to a string, and how are the resulting parts accessed? - In the form validation example, what three empty-field checks are performed first, and what happens if any is empty?
- How does the
onSubmit="return checkValues()"attribute in the form tag control whether data is sent to the server?
π Lecture 16 β JAVA SCRIPTING AND XML
π Overview: This lecture covers two main areas: first, using JavaScript's
forloop to validate user inputs in web forms, including checking for invalid characters and password matching; second, introducing XML (Extensible Markup Language) as a powerful alternative to HTML for data management, including its syntax rules, embedding in HTML, and styling with XSL. Understanding these topics is crucial for creating robust, data-driven web applications.
ποΈ Topics Covered
The lecture begins by demonstrating how JavaScript's for loop can be employed in a registration form to check for invalid characters like commas in a user login field and to verify that two entered passwords match. It then introduces XML, explaining its creation by the W3C, its advantages over HTML for data management, and its fundamental differences: user-defined tags and semantic meaning. The lecture details XML syntax rules, methods for embedding XML in HTML documents, and the use of XSL (Extensible Stylesheet Language) for formatting XML data, concluding with a comparison of HTML and XML editors.
π Lecture Summary
JAVA SCRIPTING AND XML
For loop can be used in the code of Registration form to check that users do not type invalid characters in the text box. For example, in case a user types a β,β in the text box for user login, an alert box can be made to display informing him that it is an invalid user login. See Fig. 1 below.
π Definition β For loop/statement: The initialization statement is executed only at the beginning of the For loopβs execution. The condition is then tested, and if it is true the statements enclosed within the curly brackets are executed. If the condition is false, the loop is terminated and the statement following the For statement is executed.
Another check can also be applied to see that the passwords entered in two different text boxes by the user are the same. In case the two passwords do not match an alert box can inform the user about it (see Fig. 2 below). In case no condition applied in the code is violated then the function checkValues returns true at βonsubmitβ. Consequently, the information provided by the user in the form is forwarded to the server side.
Extensible markup language
World Wide Web Consortium (W3C), a non-profit organization that maintains standards for the web presented the draft of XML in late 1990βs. It is also used for web page creation and includes data management capabilities that HTML cannot provide. Consider the example of a list of planets. Suppose that same HTML heading tags are decided to be used each planet. Also, suppose that it is decided to display different pieces of information about a planet in different heading sizes. Then, there is a shortcoming in respect of HTML that it can only supply upto 6 different levels of headings. In case there are more than six different pieces of information to display, then HTML loses its efficacy. That is why web professionals have found XML as a list formatting alternative of HTML.
π Formula: The key difference between HTML and XML: HTML has predefined tags and formats appearance; XML allows user-defined tags that convey meaning.
XML differs from HTML in two important respects:
- XML is not a markup language with defined tags; rather, one can create oneβs own set of tags in XML.
- XML tags do not provide information how text would appear on a web page. Instead of that XML tags convey meaning of information included within them.
First line of the XML code is a declaration that it is an XML document (version 1). The second and last lines of the code are called root element tags. We enclose other elements within the root element tags. Other elements are called child elements. Names of child elements can be different between two organizations, which can make the sharing of information difficult. This has led to the necessity of having uniform standards for writing different types of XML documents. Many companies have agreed to follow common standards for XML tags. A file that uses XML tags is called data type definition (DTD) or XML schema. Different DTDs are available for different industries.
Rules for writing an XML code
- All elements must be properly nested
<outer><inner>content</inner></outer> - All attribute values must be quoted
<FRIES SIZE="LARGE"> - All elements with empty content must be identified by ending in
/><BR/>,<img src="image2.gif" /> - All elements must be cased consistently
<PART>must not be closed as</part> - Certain characters having reserved meanings cannot be used e.g,
&,<etc.
Embedding XML into HTML documents
<XML> element can be used anywhere within HTML document to enclose XML content. Also, <script> element can be used for such purpose e.g, <script language="xml" type="text/xml">......</script>
Extensible Style sheet Language (XSL)
XML files are translated using another file which contains formatting instructions. Formatting instructions are often written in Extensible Style sheet Language (XSL). These formatting instructions are read over by special programs β usually these programs are written in Java programming language - called XML Parsers.
We write XSL rules that match various XML elements. Note that we use <rule> elements and <target-element> in our XSL code to provide formatting instructions for the corresponding XML elements.
HTML and XML editors
General purpose text-editors for HTML are Notepad, Wordpad etc. However, there are certain HTML editors that help create web pages more easily, e.g, Macromedia Dreamweaver and Microsoft FrontPage. XML code can also be written in any general purpose text editor. However, there are special programs such as Epic Editor, TurboXML which can facilitate the editing job considerably.
β Key Takeaways
The for loop in JavaScript is essential for iterating through form inputs to validate data, such as checking for invalid characters like commas and ensuring password fields match. XML was developed by the W3C to overcome HTML's limitations in data management, as it allows users to define their own tags that describe the meaning of data, not its appearance. XML documents must follow strict syntax rules, including proper nesting, quoted attribute values, consistent casing, and the use of root and child elements. To format XML for display, XSL (Extensible Stylesheet Language) is used, where rules with <rule> and <target-element> tags are written to style specific XML elements. While XML can be written in any text editor, specialized tools like Epic Editor and TurboXML significantly ease the process.
π§ Quick Revision Questions
- How can a JavaScript
forloop be used to validate user input in a registration form? - What are the two key differences between HTML and XML in terms of tags and purpose?
- List five mandatory rules for writing valid XML code.
- How can XML content be embedded directly into an HTML document?
- What is the role of XSL (Extensible Stylesheet Language) and XML Parsers in processing an XML file?
π Lecture 17 β Client and Server Side Processing of Data
π Overview: This lecture explains the two-way client-server communication model, detailing what processing occurs on each side. It focuses on client-side technologies like JavaScript and applets, with special emphasis on cookiesβhow they are created, stored, and used for tracking customers and maintaining session state. Understanding this division of labor is critical for designing efficient web applications.
ποΈ Topics Covered
Client-side data processing includes HTML rendering, JavaScript execution, applets, and cookies stored on the user's hard disk. Server-side processing handles database queries and complex logic. The lecture demonstrates cookie creation via JavaScript, explains cookie usage for customer tracking and session state maintenance, and distinguishes between fat clients (heavy client processing) and thin clients (minimal client processing).
π Lecture Summary
Client side processing
Data processed on the client side includes HTML code, most JavaScript, applets, and cookies (in most cases). The browser interprets HTML tags and executes JavaScript for simple calculations and pattern checking, as seen in earlier calculator and registration form examples. Applets are compiled Java programs sent from the server to the browser for execution, such as animation files, games, and spreadsheets. An applet is called using the <APPLET> tag with the CODE attribute pointing to the applet's URL, plus WIDTH and HEIGHT attributes for display space.
π Example: Applet call code
<HTML> <BODY>
<APPLET CODE=http://www.xyz.com/carfind.class width=100 height=200>DEMO</APPLET>
</BODY> </HTML>
Cookies
Cookies are text files stored on the client's hard disk, sent by the server side due to cookie-related programming. They are usually generated by JavaScript or CGI scripts. In JavaScript, the document.cookie property creates a cookie. When a user clicks a button, a function like updateCookie() creates the cookie, then location.reload(true) refreshes the page to display the new cookie value.
π Example: Cookie creation code
<SCRIPT LANGUAGE="JavaScript">
function updateCookie() {
document.cookie = document.form1.cookie.value;
location.reload(true);
}
</SCRIPT>
<FORM NAME="form1">
This information would be treated as a Cookie: <INPUT TYPE="TEXT" NAME="cookie" size="50">
<INPUT TYPE="Button" VALUE="Set Cookie!" onclick="updateCookie()">
</FORM>
When a user types "Ahmad" and clicks "Set Cookie," the cookie 'Ahmad' is created and stored on the hard disk.
π Definition β Cookie: A text file stored on the client's hard disk by the server, used to store small pieces of data like user preferences or unique IDs.
Uses of Cookies
Cookies are used to track customers online. A unique ID is stored in the cookie file on the hard disk, and the same ID is stored in the merchant's database along with the customer's purchase history. When the customer revisits, the browser transmits the cookie to the server, which matches the ID with the database, allowing personalized recommendations in real time.
Cookies also maintain state between broken sessions. Information from a previous session (e.g., form data) can be stored in the cookie and made available to the server in a subsequent session. The expires attribute sets the cookie's expiration date.
π Example: Storing multiple variables with expiration
firstName = document.form1.first.value;
lastName = document.form1.last.value;
email = document.form1.email.value;
expirationDate = "Friday, 01-Dec-11 12:00:00 GMT";
document.cookie = "firstname=" + firstname + ";lastname=" + lastname + ";email=" + email + ";expires=" + expirationDate;
π‘ Why this matters: Cookies are fundamental for e-commerce personalization, shopping carts, and maintaining user login state across page visits.
Fat vs. Thin Client
Fat clients perform a lot of processing on the client side, while thin clients perform minimal client-side processing, with most work done on the server side.
π Definition β Fat Client: A client machine that handles significant processing, such as running applets or complex JavaScript, reducing server load but requiring more client resources.
π Definition β Thin Client: A client machine that does minimal processing, relying heavily on the server for data handling and logic, typical of simple browsers.
β Key Takeaways
Client-side processing includes HTML, JavaScript, applets, and cookies. Cookies are text files stored on the client's hard disk, created using document.cookie in JavaScript, and used for customer tracking by storing a unique ID matched against a server database. Cookies also maintain state between sessions by storing form data with an expiration date. Applets are called via the <APPLET> tag with CODE, WIDTH, and HEIGHT attributes. The fat vs. thin client distinction depends on how much processing occurs on the client versus the server.
π§ Quick Revision Questions
- What are the main data types processed on the client side?
- How is a cookie created in JavaScript, and what property of the document object is used?
- Name two practical uses of cookies in e-commerce.
- How does the
<APPLET>tag specify the location of the applet code? - What is the difference between a fat client and a thin client?