0% found this document useful (0 votes)
399 views289 pages

Birla Institute of Technology & Science, Pilani: Work Integrated Learning Programmes

The document provides a course handout for a "Web Technologies" course, including: - An overview of the course which introduces web development technologies like HTML, CSS, JavaScript, and servers. - Course objectives related to learning client-side and server-side technologies, designing web pages, developing simple applications, and web server administration. - A content structure that breaks the course into 8 modules covering topics like HTML, CSS, JavaScript, servers, and PHP. - 4 learning outcomes related to developing web pages, applications, server setup, and debugging. - A contact session plan that follows a flipped learning model with recorded lectures and contact sessions focusing on exercises and homework.

Uploaded by

Ajay Gowtham
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
399 views289 pages

Birla Institute of Technology & Science, Pilani: Work Integrated Learning Programmes

The document provides a course handout for a "Web Technologies" course, including: - An overview of the course which introduces web development technologies like HTML, CSS, JavaScript, and servers. - Course objectives related to learning client-side and server-side technologies, designing web pages, developing simple applications, and web server administration. - A content structure that breaks the course into 8 modules covering topics like HTML, CSS, JavaScript, servers, and PHP. - 4 learning outcomes related to developing web pages, applications, server setup, and debugging. - A contact session plan that follows a flipped learning model with recorded lectures and contact sessions focusing on exercises and homework.

Uploaded by

Ajay Gowtham
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 289

BIRLA INSTITUTE OF TECHNOLOGY & SCIENCE, PILANI

WORK INTEGRATED LEARNING PROGRAMMES


COURSE HANDOUT

Part A: Content Design


Course Title Web Technologies
Course No(s) CSI ZG526
Credits 4
Author AKSHAYA GANESAN
Version 1.0

Course Description
The course introduces technologies related to web development and associated technologies that
makes the web work. It introduces descriptive languages like HTML, CSS and the de facto scripting
language JavaScript which powers all dynamic websites today. Focus on both client and server-side
technologies is covered to provide an understanding of the full stack. Server administration topics
helps to understand how web applications are setup on server. Protocols that are used to exchange
information and various web information formats are also added. This helps to gain an
understanding of how web applications are designed and how to develop simple web applications
that could query database and fetch information over the network and debug the same.

Course Objectives
No Objective

CO1 Learn client side and server side technologies and associated components involved at both client
and server end.

CO2 Learn the structure of web page and how to design the same using HTML and CSS. Able to
understand and write client side scripts on a web page using JavaScript.

CO3 Understand 3-tier client-server architecture and learn how to develop simple web applications
with a web interface to accepts inputs and process them accordingly

CO4 Learn working of a web server and the corresponding administration for publishing and managing
web applications written in PHP.

Text Book(s)
No Author(s), Title, Edition, Publishing House
T1 Robert W. Sebesta, Programming the World Wide Web, 7th Ed, Pearson

Reference Book(s) & other resources


No Author(s), Title, Edition, Publishing House
R1 Harvey M. Deitel and Paul J. Deitel, Internet & World Wide Web How to Program, 4th
Ed, Prentice Hall
R2 Web reference - Mozilla Developer Network
1. Web technology for developers - https://developer.mozilla.org/en-US/docs/Web
2. Learn web development - https://developer.mozilla.org/en-US/docs/Learn
3. HTML - https://developer.mozilla.org/en-US/docs/Web/HTML
4. CSS - https://developer.mozilla.org/en-US/docs/Web/CSS
5. JavaScript - https://developer.mozilla.org/bm/docs/Web/JavaScript

PHP
http://php.net/manual/en/getting-started.php

Content Structure
No Title of the Module References
M1 Introduction to Web technologies: T1 - Chapter 1,
• What is Internet - History of the Internet and World Wide Web, World R1 - Chapter 2
Wide Web Consortium (W3C)
• Web Servers, Web browsers
• Addressing, IP Address, Domain names, DNS Lookup, Uniform
Resource Locator (URL), URL Paths
• Protocols - HTTP, HTTPS, FTP
• Web developer languages - HTML, CSS, XML, JavaScript, PHP
M2 HTML: T1 - Chapter 2,
• HTML and XHTML R1 - Chapter 4
• HTML Basics - Boilerplate HTML5 document and its structure
• HTML5 document structure and basic text mark up
• XHTML document validation
• Image formats and Image element
• Hypertext Links
• Lists
• Tables and Table sections
• Forms and Form elements - select, textarea, button, complete form
• meta elements
• HTML5 new Elements
• HTML5 Web APIs
M3 Cascading Style Sheets: T1 - Chapter 3,
• Level of style sheets, style specification formats R1 - Chapter 5
• Selector Forms - Simple, Class, Generic, id, Contextual, Pseudo,
Universal
• Property-value forms
• Font Properties
• List Properties
• Text Alignment
• Color
• Box Model and Text Flow
• Background images
• <span> and <div> tags
• Conflict resolution
M4 JavaScript Basics: T1 - Chanter 4,
• Overview of JavaScript and its uses R1 - Chapter 6,
• Object Orientation and JavaScript 7, 8, 9, 10, 11
• Primitives, Operations, and Expressions
• Screen output and Keyboard input
• Control statements
• Object creation and modification
• Arrays
• Functions
• Errors in Scripts
M5 JavaScript and Document Object Model: T1 - Chapter 5,
• The Document Object Model (DOM) R1 - Chapter 12,
• Element access 13
• Events and event handling
• Handling events - Body elements, button elements, textbox, password
• DOM 2 Event Model
• DOM Tree Traversal and Modification
• DOM Collections
• Dynamic Styles
M6 XML: T1 - Chapter 7,
• Syntax and XML document structure R1 - Chapter 14
• Document Type Definitions (DTD)
• Namespaces
• XML Schemas
M7 Web Servers: R1 - Chapter 21
• What are Web Servers - Introduction
• HTTP transactions
• Multitier Application Architecture
• Client-side Scripting versus Server-Side Scripting
• Accessing Web Servers
• Case Study 1 - Microsoft Internet Information Server (IIS)
• Case Study 2 - Apache HTTP Server
M8 Server Side Scripting with PHP: T1 - Chapter 9,
• General Syntactic Characteristics R1 - Chapter 23
• Primitives, Operations, and Expressions, Outputs
• Control Statements
• Arrays
• Functions
• Form handling, Form Processing and Business Logic
• Connecting to Database
• Dynamic Content

Learning Outcomes:

No Learning Outcomes

LO1 Demonstrate how to develop a simple web pages using HTML and CSS and JavaScript to
accepts user inputs and validate them at client side using JavaScript.

LO2 Develop simple web applications using PHP to receive inputs from client side and able to
fetch information from backend e.g. database.

LO3 Understand how to setup a web server, publish a web application and manage it.

LO4 Understand server side logs and how to debug simple web applications and rectify the
problems in them.

Part B: Contact Session Plan


Academic Term First Semester 2019-2020

Course Title Web Technologies

Course No CSI ZG526

Lead Instructor AKSHAYA GANESAN


Glossary of Terms
1. Contact Hour (CH) stands for a hour long live session with students conducted either in a physical
classroom or enabled through technology. In this model of instruction, instructor led sessions will
be for 22 CH.
a. Pre CH = Self Learning done prior to a given contact hour
b. During CH = Content to be discussed during the contact hour by the course instructor
c. Post CH = Self Learning done post the contact hour
2. Contact Hour (CS) stands for a two-hour long live session with students conducted either in a
physical classroom or enabled through technology. In this model of instruction, instructor led
sessions will be for 11 CS.
a. Pre CS = Self Learning done prior to a given contact session
b. During CS = Content to be discussed during the contact session by the course instructor
c. Post CS = Self Learning done post the contact session
3. RL stands for Recorded Lecture or Recorded Lesson. It is presented to the student through an
online portal. A given RL unfolds as a sequences of video segments interleaved with exercises
4. SS stands for Self-Study to be done as a study of relevant sections from textbooks and reference
books. It could also include study of external resources.
5. LE stands for Lab Exercises
6. HW stands for Home Work.
7. M stands for module. Module is a standalone quantum of designed content. A typical course is
delivered using a string of modules. M2 means module 2.

Teaching Methodology (Flipped Learning Model)


The pedagogy for this course is centered around flipped learning model in which the traditional class-room
instruction is replaced with recorded lectures to be watched at home as per the student’s convenience and
the erstwhile home-working or tutorials become the focus of classroom contact sessions. Students are
expected to finish the home works on time.

Contact Session Plan


o Each Module (M#) covers an independent topic and module may encompass more than one
Recorded Lecture (RL) or Lecture Segment (LS).
o Contact Sessions (2hrs each week) are scheduled alternate weeks after the student watches all
Recorded Lectures (RLs) of the specified Modules (listed below) during the previous week
o In the flipped learning model, Contact Sessions are meant for in-classroom discussions on cases,
tutorials/exercises or responding to student’s questions/clarification--- may encompass more than
one Module/RLs/CS topic.
o Contact Session topics listed in course structure (numbered CSx.y) may cover several RLs; and as
per the pace of instructor/students’ learning, the instructor may take up more than one CS topic
during each of the below sessions.

Detailed Structure
Introductory Video/Document: << Introducing the faculty, overview of the course, structure and
organization of topics, guidance for navigating the content, and expectations from students>>

Each of the sub-modules of Recorded Lectures (indicated by RLx.y / LS x.y / LSx.yVz) shall
delivered via 30 – 60mins videos followed by:
Contact session (CSx.y) of 2Hr each for illustrating the concepts discussed in the videos with
exercises, tutorials and discussion on case-problems (wherever appropriate); contact sessions (CS)
may cover more than one recorded-lecture (RL) videos.
Course Contents
<From content structure in Part A of this document. Detail the plan of delivery across each contact
hour or each contact session. 1 contact session = 2 contact hours>

Time Type Description References


Module 1 Introduction to Web Technologies
Pre-CH/CS RL 1.1 RL1.1 Introduction to Web
RL1.2
• RL1.1.1 Internet and WWW
• RL1.1.2 URL
RL 1.2 HTTP

• RL1.2.1 Introduction to HTTP


• RL1.2.2 HTTP Methods
• RL1.2.2 Demo
• RL1.2.3 HTTP Headers

During CS 1 • Addressing, IP Address, Domain names, DNS T1 - Chapter 1,


CH/CS Lookup, R1 - Chapter 2
• Uniform Resource Locator (URL), URL Paths Web
• Protocols - HTTP, HTTPS , FTP technology for
• Introduction to Web developer languages - developers -
HTML, CSS, XML, JavaScript, PHP https://develop
er.mozilla.org/
en-
US/docs/Web

Post- HW/Lab Exercises Use Curl to generate HTTP Request


CH/CS Understand about Developer tools of Web browser
Lab Lab Capsule 1 Module 1 Lab Sheet HTTP
Reference
Module 2 HTML
Pre-CH/CS RL 2.1 RL2.1 HTML
RL 2.2 • RL2.1.1 HTML STRUCTURE
RL 2.3 • RL 2.1.2 BASIC TAGS
• RL 2.1.2 Demo
RL2.2 HTML5
• RL2.2.1 HTML5 Semantic Elements
• RL2.2.2 HTML FORMS
• RL2.2.2 Demo
RL2.3 HTML5 Web API
• RL2.3.1 Web APIs
RL2.3.1 Demo
During CS2 • Creating Web Pages using HTML5 document T1 - Chapter 2,
CH/CS structure and tags R1 - Chapter 4
• HTML Boilerplate HTML5 document and its Web
structure technology for
• HTML document validation developers -
• Creating FORMS using HTML https://develop
• HTML5 Web APIs er.mozilla.org/
en-
US/docs/Web

Post- HW/Lab Practice Creating simple Web pages using HTML


CH/CS
Lab Lab Capsule 2 Module 2 Lab Sheet for HTML
Reference
Module 3 Cascading Style Sheets
Pre-CH/CS RL3.1 RL 3.1 CSS
RL3.2 • RL3.1.1 CSS
• RL3.1.1 Demo
• RL3.1.2 CSS Selectors
• RL3.1.3 Demo
• RL 3.1.3 Box Model and Postioning
• RL3.1.4 Colors
RL 3.2 Cascasde
• RL3.2.1 Cascade Algorithm and Inheritance
During CS 3 • Apply Styles and colors to Web pages using T1 - Chapter 3,
CH/CS various selectors. R1 - Chapter 5
• Demonstrate the positioning of elements in Web
pages using CSS
• Illustrate how conflict resolution happens using
examples
Post- HW/Lab Apply styles to web pages created
CH/CS
Lab Lab Capsule 3 Module 3 Lab Sheet Using CSS
Reference
Module 4 Javascript
Pre-CH/CS RL4.1 RL 4.1 Javascript
RL4.2 • RL 4.1.1 Javascript Basics
• RL 4.1.2 Javascript Arrays and Fucntions
RL 4.2.1 Javascript Objects
During CS 4 • Primitives, Data types, Operator and Expressions T1 - Chapter 4,
CH/CS • Control statements R1 - Chapter 6,
• Object creation and modification 7, 8, 9, 10, 11
• Errors in Scripts
• Demonstration to use Arrays, functions in
Javascript
Post- HW/Lab Understand the console window of Developer tools in
CH/CS Chrome Browser
Lab Lab Capsule 4 Module 4 Lab Sheet – Javascript Basics
Reference
Module 5 Javascript and DOM
Pre-CH/CS RL 5.1 RL 5.1 DOM
• RL5.1.1 Using DOM
• RL 5.1.1 Demo
• RL5.1.2 Event Handling
• RL5.1.2 Demo 1
• RL5.1.2 Demo 2
• RL5.1.2 Demo 3
During CS5 • Handling events T1 - Chapter 5,
CH/CS • DOM 2 Event Model R1 - Chapter
• DOM Tree Traversal and Modification 12, 13
• DOM Collections
• Demonstrate examples to modify , add elements in
webpage using DOM.
• Demo of Registering events to elements
Post- HW/Lab Understand the Difference between the various DOM
CH/CS versions
Lab Lab Capsule 5 Module 5 Lab Sheet- Using DOM
Reference
Module 6 XML
Pre-CH/CS RL 6.1 RL6.1 XML
RL 6.2 • RL6.1.1 Basic XML
RL 6.3 RL6.2 DTD
• RL6.2.1 DTD
RL6.3 XML Schema
• RL6.3.1 XML Schema
• RL6.3.1 Demo
During CS6 • Demonstrate creating XML documents for given T1 - Chapter 7,
CH/CS Schema. R1 - Chapter 14
• Creating DTD documents
• Add restriction on content using XML Schema
• Validating XML documents

Post- HW/Lab Compare XML and JSON


CH/CS
Lab Lab Capsule 6 Module 6 Lab Sheet- XML
Reference
Module 7 Web Servers
Pre-CH/CS RL 7.1 RL7.1 Web Server
RL 7.2 • RL7.1.1 Web Server
RL7.2 Apache Web Server
• RL7.2.1 Apache Web Server
• RL7.2.1 Demo 1
• RL7.2.1 Demo 2
During CS7 • Accessing Web Servers R1 - Chapter 21
CH/CS • Case Study 1 - Microsoft Internet Information
Server (IIS)
• Case Study 2 - Apache HTTP Server
• Configuring Web Servers
• Demonstrate of host websites on Web Server
• Virtual Hosting
Post- HW/Lab Comparative study of different web servers
CH/CS
Lab Lab Capsule 7 Module 7 Lab Sheet- Web Server Configuration
Reference
Module 8 Server Side Scripting
Pre-CH/CS RL 8.1 RL8.1 PHP
RL 8.2 • RL8.1.1 Server Side Programming
• RL8.1.2 Introduction to PHP
• RL 8.1.3 PHP Data Types
• RL8.1.3 Demo
RL8.2 Server Side Processing
• RL8.2.1 Form Processing
• RL8.2.2 Cookies and Session
• RL8.2.2 Demo
During CS8 • Client Side vs Server Side Scripting T1 - Chapter 9,
CH/CS • Example to demonstrate Primitives, R1 - Chapter 23
Operations, Expressions, Outputs and Control PHP
Statements in PHP http://php.net/m
• Demonstrate form processing on server side.
anual/en/getting
• Handling cookies and sessions
-started.php

Post- HW/Lab Study the advantages of different server side languages


CH/CS
Lab Lab Capsule 8.1 Module 8.1 Lab Sheet- Server Side Scripting
Reference
Module 8 Server Side Scripting
Pre-CH/CS RL 8.3 RL8.3 DatabaseConnectivity
• RL8.3.1Connecting to Database
• RL8.3.1 Demo

During CS9 • Connecting to Database from PHP T1 - Chapter 9,


CH/CS • Prepared Statements R1 - Chapter 23
• Demonstrate the database connection

Post- HW/Lab
CH/CS
Lab Lab Capsule 8.2 Module 8.2 Lab Sheet- Database connection using PHP
Reference
CS10 : Review Session

Lab Details
Lab No Lab Objective Lab Sheet/Capsule Content Reference
Access URL
1 To understand the HTTP T1 - Chapter 1,
request and Response R1 - Chapter 2

2 Create Web pages using T1 - Chapter 2,


HTML R1 - Chapter 4

3 Apply Styles to Web Pages T1 - Chapter 3,


using CSS R1 - Chapter 5

4 Exercises on JavaScript to T1 - Chapter 4,


validate client side form R1 - Chapter 6,
processing logic 7, 8, 9, 10, 11
5 Exercises using JavaScript T1 - Chapter 5,
to navigate DOM R1 - Chapter
programmatically. 12, 13

6 Create valid and Well T1 - Chapter 7,


Formed XML documents R1 - Chapter 14

7 Configure Web servers and R1 - Chapter 21


host simple web sites on
server

8 8.1 Exercises using PHP to T1 - Chapter 9, R1 -


process server side logic Chapter 23

8.2 Database connection with


PHP

Select Topics and Case Studies from business for experiential learning

Topic Select Topics in Syllabus for experiential learning Access URL


No.
1 Design web pages using HTML5 to explore commonly used T1, R1
standard markup elements.

2 Create cascading styles styles and apply them to the HTML pages T1, R1
designed above.

3 Exercises on JavaScript to validate client side form processing logic. T1, R1

4 Exercises using JavaScript to navigate DOM programmatically. T1, R1

5 Exercises using PHP to process server side logic and connect and T1, R1
fetch database contents.

Evaluation Scheme
Legend: EC = Evaluation Component
No Name Type Duration Weight Day, Date, Session, Time
EC-1 Quiz-I Online - 5% August 23 – September 01,
2019
Quiz-II Online 5% September 27 – October 6,
2019
Assignment-I Online 15% November 01 – 10, 2019
EC-2 Mid-Semester Test Closed Book 2 hours 30% Sunday, 22/09/2019 (FN)
10 AM – 12 Noon
EC-3 Comprehensive Open Book 3 hours 45% Sunday, 17/11/2019 (FN)
Exam 9 AM – 12 Noon

Note - Evaluation components can be tailored depending on the proposed model.


Important Information:
Syllabus for Mid-Semester Test (Closed Book): Topics in CS 1-5.
Syllabus for Comprehensive Exam (Open Book): All topics given in plan of study
Evaluation Guidelines:
1. For Closed Book tests: No books or reference material of any kind will be permitted.
Laptops/Mobiles of any kind are not allowed. Exchange of any material is not allowed.
2. For Open Book exams: Use of prescribed and reference text books, in original (not photocopies) is
permitted. Class notes/slides as reference material in filed or bound form is permitted. However,
loose sheets of paper will not be allowed. Use of calculators is permitted in all exams.
Laptops/Mobiles of any kind are not allowed. Exchange of any material is not allowed.
3. If a student is unable to appear for the Regular Test/Exam due to genuine exigencies, the student
should follow the procedure to apply for the Make-Up Test/Exam. The genuineness of the reason
for absence in the Regular Exam shall be assessed prior to giving permission to appear for the
Make-up Exam. Make-Up Test/Exam will be conducted only at selected exam centres on the dates
to be announced later.
It shall be the responsibility of the individual student to be regular in maintaining the self-study schedule as
given in the course handout, attend the lectures, and take all the prescribed evaluation components such as
Assignment/Quiz, Mid-Semester Test and Comprehensive Exam according to the evaluation scheme
provided in the handout.
Birla Institute of Technology & Science, Pilani
Work-Integrated Learning Programmes Division
Second Semester 2017-2018

Mid-Semester Test
(EC-2 Regular)

Course No. : CSI ZG526


Course Title : Web Technologies
Nature of Exam : Closed Book No. of Pages =2
Weightage : 30% No. of Questions = 10
Duration : 2 Hours
Date of Exam : 30/09/2018 FN
Note:
1. Please follow all the Instructions to Candidates given on the cover page of the answer book.
2. All parts of a question should be answered consecutively. Each answer should start from a fresh page.
3. Assumptions made if any, should be stated clearly at the beginning of your answer.

Q.1) A web browser at a client accesses a static HTML webpage from a web server S. The HTML
page contains exactly one static image which is also at S. Assuming no caching, how many HTTP
requests needs to be sent from the client to web server S to load the HTML page? Explain your
answer [2]

Q.2) A user request for a web page at a URL, but the page is no longer available at the indicated
URL. What will be the web server’s HTTP response? Can the web browser automatically download
the right web page from the new URL? [3]

Q.3) i) What is the purpose of HTTP TRACE method? How will the web server respond to a HTTP
TRACE Request? [3]
ii) Which HTTP method is suitable for obtaining Meta information about the web page without
transferring the HTML contents? How it will be useful? [2]

Q.4) Create an HTML page which contains the following definition list. [3]

HTTP
HyperText Transfer Protocol
FTP
File Transfer Protocol
SMTP
Simple Mail Transfer Protocol
POP
Post Office Protocol

Q.5) What is the use of preload attribute in the HTML video element? What are the attribute
values it can have? [3]
Q.6) If your CSS doesn't set the width and height of an element, how is the width and height of that
element determined? [2]

Q.7) Explain the difference between a CSS position of fixed and absolute. [2]

Q.8) Is it possible to change the transparency of an element's background without affecting the child
elements using the opacity property? If yes, mention how it can be done. If no, suggest alternate method to
do the same [3]

Q.9) What does the following JavaScript print in the console? [3]

var x=1;
(function(x){
console.log(x);
x=3;
})(2);
console.log(x);

Q.10) Write a JavaScript program to display the current day and time in a webpage. [4]

******************
Birla Institute of Technology & Science, Pilani
Work-Integrated Learning Programmes Division
Second Semester 2018-2019
Mid-Semester Test (EC-2 Regular)

Course No. : CSI ZG526


Course Title : WEB TECHNOLOGIES
Nature of Exam : Closed Book
Weightage : 30% No. of Pages =2
Duration : 2 Hours No. of Questions = 10
Date of Exam : 10/03/2019 (FN)
Note:
1. Please follow all the Instructions to Candidates given on the cover page of the answer book.
2. All parts of a question should be answered consecutively. Each answer should start from a fresh page.
3. Assumptions made if any, should be stated clearly at the beginning of your answer.

Q.1. Answer the following questions based on HTTP Methods.


(a) How does the CONNECT Method establish a two way communication with the server
(b) What is an idempotent method? Mention the idempotent methods in HTTP?
(c) Which header lists the set of methods support by a resource or the entire web server in
an HTTP response? [2 + 2 + 2 = 6]

Q.2. Explain about the information sent in the ‘Client Hello’ message in a TLS handshake? [2]

Q.3. What is a PTR record in DNS? [2]

Q.4. The anchor <a> tag in HTML supports an attribute named target. For example, a link to the
Google search page could be written as:
<a target=”_blank” href=http://www.google.com>Google</a>
What is the purpose of the target attribute? What will be the change in the behavior, if the
target attribute takes the values _self, _blank, _top and _parent? [3]

Q.5. What is the use of a novalidate attribute and autocomplete attribute for the form tag that was
introduced in HTML5? [2]

Q.6. Write a HTML code to create a form exactly as shown below. The form contains one drop
down menu, one date selector along with send and reset buttons. [5]

Q.7. How will the total width and total height of an element be calculated according to the box
model? Calculate the total width and height of the div element with the following CSS code
[2]
div {
width: 320px;
padding: 10px;
border: 5px solid gray;
margin: 0;
}

CSI ZG526 (EC-2 Regular) Second Semester 2018-2019 Page 1 of 2


CSI ZG526 (EC-2 Regular) Second Semester 2018-2019 Page 2

Q.8. Q.8.
<html>
<body>
<div id="div1">Web</div>
<div id="div2" class="class1">BITS-Pilani</div>
<div>
<span id="span1" class="class1">WILP</span>
<span id="span2" class="class2">Exam</span>
</div>
</body>
</html>
Illustrate what will be the changes in text color for the words (Web, BITS-Pilani, WILP,
Exam) in the above HTML page, when the following CSS rules are applied. [4]
i. div { color: red}
div.class1 {color: green}
ii. #span2 {color: yello}

Q.9. What will be the output of the javascript code below? [2]

var trees = ["redwood","bay","cedar","oak","maple"];


delete trees[3];
console.log(trees);

Q.10. What will be the output of the javascript code below? [2]

var bar = true;


console.log(bar + 0);
console.log(bar + "xyz");
console.log(bar + true);
console.log(bar + false);

**********

CSI ZG526 (EC-2 Regular) Second Semester 2018-2019 Page 2 of 2


CSI ZG526 Web Technologies
I Sem 2019-20
Akshaya Ganesan
BITS Pilani Asst. Prof[Off-Campus]
BITS-Pilani
Learning Objectives

Learn client side and server side technologies and associated components involved at both client and
server end.

Learn the structure of web page and how to design the same using HTML and CSS. Able to understand
and write client side scripts on a web page using JavaScript.

Understand 3-tier client-server architecture and learn how to develop simple web applications with a web
interface to accepts inputs and process them accordingly

Learn working of a web server and the corresponding administration for publishing and managing web
applications written in PHP.

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Readings

Text and Reference Books


No Author(s), Title, Edition, Publishing House
T1 Robert W. Sebesta, Programming the World Wide Web, 7th Ed, Pearson

No Author(s), Title, Edition, Publishing House


R1 Harvey M. Deitel and Paul J. Deitel, Internet & World Wide Web How to Program,
4th Ed, Prentice Hall

Web reference - Mozilla Developer Network


https://developer.mozilla.org/

CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
19/07/2019
Course Overview

Basic understanding of the Web : HTTP, URL


Static Client Content
• HTML
• CSS

Dynamic Client Content


• JavaScript, DOM

XML
Web Servers
Server Side Scripting
• PHP

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
BITS Pilani
Hyderabad Campus

Lecture 1.1: Introduction to Web


World Wide Web

The World Wide Web is a primary application program on the Internet.


The Internet is a collection of computers provides many services
World Wide Web, electronic mail, multiplayer online games, Internet telephony,
file sharing and streaming media services.
Origin
– Tim Berners-Lee at CERN proposed the Web in 1989
Sharing information via hyperlinked text documents.
Documents(Web Pages) and other web resources are identified by Uniform
Resource Locators (URLs).
Web pages are annotated with Hypertext Markup Language (HTML).
Web pages may contain images, video, audio, and software components.
6

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Client –Server Architecture

The Web operates in client-server architecture.


Web clients, or browsers
– A browser is a client on the Web because it initiates the communication with a web server
Web Servers
– Web servers are programs that provide documents to requesting browsers.

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Three essential technologies of Web

A system of globally unique identifiers for resources on the Web :Uniform


resource locator (URL).
The publishing language HyperText Markup Language (HTML).
The Hypertext Transfer Protocol (HTTP): a communications protocol used to
send information over the web

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Working of the Web

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
URL (Uniform Resource Locator)

A URL (Uniform Resource Locator) is used to uniquely identify a resource over


the web.
Each valid URL points to a unique resource.
Such resources can be an HTML page, a CSS document, an image, etc
URL Formats
scheme:object-address
The scheme is a communication protocol.
Common schemes include http, ftp, gopher, telnet, file, mailto
In the case of HTTP, the form of the object address of a URL is as follows:
http://fully-qualified-domain-name/path-to-document?query#fragment
When file is the protocol, the form of such URLs as follows:
10
file://path-to-document CSIZG526 Web Technologies
19/07/2019 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Parts of a URL

Fully qualified Domain name


Fully qualified Domain name is the name of the web-server(hostname) on which
the resource resides.
The web server is referred to as the host, because it houses and maintains
resources.
The hostname is translated into an IP (Internet Protocol) address
A 32 bit-numerical value that uniquely identifies the server on the Internet.
An Domain Name System (DNS) server maintains a database of hostnames
and their corresponding IP addresses.
Example : www.bits-pilani.ac.in/pilani/library

11

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Parts of a URL

PORT NUMBER
The default port number of HTTP is 80.
If a server has been configured to use some other port number, it is necessary
to attach that port number to the hostname in the URL.
Example : www.bits-pilani.ac.in:8080
Path-and-file-name
The name and location of the requested resource, under the server document
base directory.
The location is typically a virtual directory.
Server maps requested URLs to the document, whose location is not known to
clients.
URLs cannot include spaces. 12

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Parts of a URL

A query string.
If a query string is used provides a string of information that the resource can
use.
The query string is usually a string of name and value pairs;
for example, term=btech.
Name and value pairs are separated from each other by an ampersand (&);
for example, term=btech&course=cse.

Fragment
The fragment is used to refer to an internal section within a web document.

13

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Example

For example,
http://www.bits-pilani.ac.in:8080/admissions/firstdegree?term=btech#h1
Communication protocol:http
Hostname: bits-pilani.ac.in
Portnumber:8080
Path: /admissions/firstdegree
Query string: term=btech
Fragment=h1
The document root in web server is :/admin/web/topdocs.
http://www.bits-pilani.ac.in:8080/admissions/firstdegree
file path /admin/web/topdocs/admissions/firstdegree 14

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
BITS Pilani
Hyderabad Campus

Lecture 1.2: HTTP

15
19/07/2019
HyperText Transfer Protocol(HTTP)

HTTP is an asymmetric request-response client-server protocol


HTTP is a stateless protocol.
HTTP is an application-level protocol for distributed, collaborative, hypermedia
information systems.
HTTP consists of two phases:
The request and the response.
Each HTTP communication (request or response) between a browser and a
Web server consists of two parts:
a header and a body.
The header contains information about the communication; the body contains
the data of the communication (optional).
16

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
HTTP(Contd…)

17

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
HTTP Request

The general form of an HTTP request is:


1. HTTP Request Line:
2. Header fields
3. Blank line
4. Message body (Optional)

18

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
HTTP Request

19

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Request Line

The first line of the header is called the request line:


request-method-name /request-URI /HTTP-version
request-method-name: HTTP methods
request-URI: specifies the resource requested.
HTTP-version: Two versions are currently in use: HTTP/1.0 and HTTP/1.1.

Examples of request line are:


GET /test.html HTTP/1.1
HEAD /query.html HTTP/1.0
POST /index.html HTTP/1.1
20

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Request Headers

The request headers are in the form of name:value pairs. Multiple values,
separated by commas, can be specified.

request-header-name: request-header-value1, request-header-value2, ...


Examples of request headers are:
Host: www.xyz.com
Connection: Keep-Alive
Accept: image/gif, image/jpeg, */*
Accept-Language: us-en, fr, cn

21

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
HTTP Response

The general form of an HTTP response is:


1. Status line
2. Response header fields
3. Blank line
4. Response body

The status line includes the HTTP version used, a three-digit status code for the
response, and a short textual explanation of the status code.

22

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
HTTP Response

23

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Status Line

The first line is called the status line.


HTTP-version status-code reason-phrase
status-code: a 3-digit number generated by the server to reflect the outcome of
the request.
reason-phrase: gives a short explanation to the status code.
Common status code and reason phrase are "200 OK", "404 Not Found", "403
Forbidden", "500 Internal Server Error".

Examples of status line are:


HTTP/1.1 200 OK
HTTP/1.0 404 Not Found
24
HTTP/1.1 403 Forbidden
19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
STATUS CODE

Status code is a three-digit number; first digit the specifies the general status

1 => Informational

2 => Success

3 => Redirection

4 => Client error

5 => Server error 25

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Response Headers

The response headers are in the form name:value pairs:

response-header-name: response-header-value1, response-header-value2, ...


Examples of response headers are:

Content-Type: text/html
Content-Length: 35
Connection: Keep-Alive
Keep-Alive: timeout=15, max=100
The response message body contains the resource data requested.
26

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
HTTP Methods

HTTP defines a set of request methods


To indicate the desired action to be performed for a given resource.
HTTP verbs
– GET.
– POST,
– HEAD,
– OPTIONS,
– PUT,
– DELETE,
– TRACE and
– CONNECT
27

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
GET Method

The GET method requests a representation of the specified resource.


Requests using GET should only retrieve data.
Example
GET /hello.htm HTTP/1.1 HTTP/1.1 200 OK
Date: Mon, 27 Jul 2018 12:28:53 GMT
User-Agent: Mozilla/4.0
Server: Apache/2.2.14 (Win32)
Host: localhost Last-Modified: Wed, 22 Jul 2018 19:15:56 GMT
Accept-Language: en-us ETag: "34aa387-d-1568eb00"
Accept-Encoding: gzip, deflate Accept-Ranges: bytes
Connection: Keep-Alive Content-Length: 88
Content-Type: text/html
The server response against the above GET request:
<html>
<body>
<h1>Hello, World!</h1>
</body> 28
</html>
19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
POST Method

The POST method is used to submit an entity to the specified resource.


It mostly causes a change in state on the server.
The POST method is used when you want to send some data to the server.
For example, file update, form data, etc.
A get request appends data to the URL, e.g., www.google.com/search?q=book.
A post request sends form data as part of the HTTP message.
A get request typically limits the query string to a specific number of characters.
To send large amounts of information use the post method.
The post method also hides the submitted data by embedding it in an HTTP
message.

29

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Example

POST /test HTTP/1.1


Host: example.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 13

say=Hi&to=John

30

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
HEAD Method

The HEAD method asks for a response identical to that of a GET request, but
without the response body.
The server replies with a response line and headers, but no entity-body
HEAD /hello.htm HTTP/1.1 HTTP/1.1 200 OK
Date: Mon, 27 Jul 2018 12:28:53 GMT
User-Agent: Mozilla/4.0
Server: Apache/2.2.14 (Win32)
Host: www.google.com Last-Modified: Wed, 22 Jul 2019 19:15:56 GMT
Accept-Language: en-us ETag: "34aa387-d-1568eb00"
Accept-Ranges: bytes
Accept-Encoding: gzip, deflate Content-Length: 88
Connection: Keep-Alive Content-Type: text/html
HEAD request is useful for checking the headers, such as Last-Modified,
Content-Type, Content-Length, before sending a proper GET request to
retrieve the document.
31

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
PUT METHOD

The PUT method is used to request the server to store the included entity-body
at a location specified by the given URL.
The PUT method replaces all current representations of the target resource with
the request payload.
PUT /hello.htm HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)
Host: www.google.com
Content-type: text/html
Content-Length: 182

<html>
<body>
<h1>Hello, World!</h1>
</body>
</html> 32

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
OPTIONS METHOD

The OPTIONS method is used to describe the communication options for the
target resource.
The OPTIONS method is used to find out the HTTP methods supported by a
web server.
The client can specify a URL for the OPTIONS method,
An asterisk (*) to refer to the entire server.
OPTIONS * HTTP/1.1
User-Agent: Mozilla/4.0

HTTP/1.1 200 OK
Date: Mon, 27 Jul 2018 12:28:53 GMT
Server: Apache/2.2.14 (Win32)
Allow: GET,HEAD,POST,OPTIONS,TRACE
Content-Type:text/html 33

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
DELETE METHOD

The DELETE method deletes the specified resource.

DELETE /hello.htm HTTP/1.1

The web servers do not enable delete method for all users

34

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
CONNECT METHOD

The HTTP CONNECT method starts two-way communications with the


requested resource.
It can be used to open a tunnel.

CONNECT www.example.com:443 HTTP/1.1

HTTP/1.1 200 Connection established


Date: Mon, 27 Jul 2018 12:28:53 GMT
Server: Apache/2.2.14 (Win32)

CONNECT is used in case of secure connection


35

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
TRACE METHOD

The TRACE method performs a message loop-back test along the path to the
target resource.
The contents of an HTTP Request is echoed back to the requester
HTTP/1.1 200 OK
It can be used for debugging purposes. Date: Mon, 27 Jul 2018 12:28:53 GMT
TRACE / HTTP/1.1 Server: Apache/2.2.14 (Win32)
Connection: close
Host: www.google.com
Content-Type: message/http
User-Agent: Mozilla/4.0 Content-Length: 39

TRACE / HTTP/1.1
Host: www.google.com
User-Agent: Mozilla/4.0

36

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
HTTP Methods

Some of the methods (for example, HEAD, GET, OPTIONS and TRACE) are,
by convention, defined as safe.
Methods PUT and DELETE are defined to be idempotent
The POST method is not idempotent.
Sending an identical POST request multiple times may further affect state
Web Browsers show dialog boxes to warn users

37

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Example 1 Misspelt Request Method

get /test.html HTTP/1.0

HTTP/1.1 501 Method Not Implemented


Date: Sun, 18 Oct 2009 10:32:05 GMT
Server: Apache/2.2.14 (Win32)
Allow: GET,HEAD,POST,OPTIONS,TRACE
Content-Length: 215
Connection: close
Content-Type: text/html; charset=iso-8859-1

38

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Example 2 : Accessing a Protected Resource

GET /forbidden/index.html HTTP/1.0


(blank line)

HTTP/1.1 403 Forbidden


Date: Sun, 18 Oct 2009 11:58:41 GMT
Server: Apache/2.2.14 (Win32)
Content-Length: 222
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=iso-8859-1 39

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
HTTP Headers –Caching-ETAG

The ETag HTTP response header is an identifier for a specific version of a resource.
If the resource at a given URL changes, a new Etag value must be generated.
ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4“

The client will send the Etag value of its cached resource along in an If-None-Match header field:
If-None-Match: "33a64df551425fcc55e4d42a148795d9f25f89d4“

The server compares the client's ETag (sent with If-None-Match) with the ETag for its current version of the
resource
If both values match, the server send back a 304 Not Modified status, without any body
Tells the client that the cached version of the response is still good.

40

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Last-Modified Header

The Last-Modified response HTTP header contains the date and time at which
the origin server believes the resource was last modified.
It is used as a validator to determine if a resource received or stored is the
same.
Less accurate than an ETag header

41

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
HTTP Headers- Connection Management
Connection Header
The Connection general header controls whether or not the network connection
stays open after the current transaction finishes.
If the value sent is keep-alive, the connection is persistent and not closed,
allowing for subsequent requests to the same server to be done.
Connection: keep-alive
Connection: close

Keep-alive Header
The Keep-Alive general header allows the sender to hint about how the
connection may be used to set a timeout and a maximum amount of
requests.
Keep-Alive: timeout=5, max=1000
42

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Redirection

In HTTP, a redirection is triggered by the server by sending special responses


to a request: redirects.
HTTP redirects are responses with a status code of 3xx.
A browser, when receiving a redirect response, uses the new URL provided in
the location header.
Location: /index.html
Permanent redirections
301 Moved Permanently
Temporary Redirections
302 Temporary Redirect

43

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
HTTP Headers-Cookies

An HTTP cookie is a small piece of data that a server sends to the user's web
browser.
The browser may store it and send it back with the next request to the same
server.
The Set-Cookie HTTP response header sends cookies from the server to the
user agent.
Set-Cookie: <cookie-name>=<cookie-value>

The Cookie HTTP request header contains stored HTTP cookies previously
sent by the server with the Set-Cookie header.
Cookie: name=value; name2=value2; name3=value3
44

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
MIME

Used to specify to browser the form of a file returned by server


attached by the server to the beginning of the document
Form: type/subtype
Examples: text/plain, text/html, image/gif, image/jpeg

Server gets type from the requested file name’s suffix


(.html implies text/html)

Browser gets the type explicitly from the server

45

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Questions?

A)Which HTTP verb should be used for


1) The client needs form submission
2) The client wants to verify the last update
3) The client needs to fect index page

B) HTTP vs HTTPS?

46

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
BITS Pilani
Hyderabad Campus

Lecture 2: HTTPS
HTTPS (Hypertext Transfer Protocol
Secure)
• Hypertext Transfer Protocol Secure is a secure version of HTTP.
• This protocol enables secure communication between a client (e.g. web
browser) and a server (e.g. web server) by using encryption.
• HTTPS uses Transport Layer Security (TLS) protocol or its
predecessor Secure Sockets Layer (SSL) for encryption.
• HTTPS is commonly used to create a secure channel over some insecure
network, e.g. Internet.
• HTTPS URLs begin with https instead of http.
• HTTPS uses a well-known TCP port 443.

48

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
HTTPS

The Transport Layer Security (TLS), and Secure Socket Layer (SSL) protocols’
main purpose is to provide
• Privacy and Integrity
• Identification and Authentication
• SSL/TLS protocol can be used in different services such as web, mail, FTP,
VoIP and VPN.
• Typically, when a service uses a secure connection the letter S is appended
to the service’s protocol name.
• For example: HTTPS, SMTPS, FTPS, SIPS.

49

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Encryption

• Symmetric Encryption
• Symmetric encryption is the process in which the same key is used for
encrypting and decrypting data.

• Asymmetric Encryption (also referred to as Public Key Cryptography) uses a


pair of keys, a public key and a private key.
• These cryptographic keys are uniquely related which means that whatever is
encrypted with one key, can be decrypted with the other.
• The public key, as the name implies, can be shared with anyone.
• The private key must be known only to the server.

50

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Certificates

When a secure connection is established, the server will send its TLS/SSL
certificate to the client.
The certificate will then be checked by the client against a trusted Certificate
Authority, essentially validating the server’s identity.
A TLS/SSL certificate essentially binds an identity to a pair of keys which are
then used by the server to encrypt as well as sign the data.
A Certificate Authority is an entity which issues TLS/SSL or Digital certificates.

51

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Certificate Authority

A Certificate Authority is a trusted third party entity which issues TLS/SSL or


Digital certificates.
These authorities have their own certificate for which they use their private
key to sign the issued TLS/SSL or Digital Certificate.
This certificate is known as the Root Certificate.
The CA’s Root Certificate, and therefore, public key, is installed and trusted by
default in browsers such as Chrome, Firefox and Edge.
This is necessary to validate that the certificate of a website visited was signed
by the CA’s private key.

52

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
TLS handshake

The SSL or TLS handshake enables the SSL or TLS client and server to
establish the secret keys with which they communicate.
• Agree on the version of the protocol to use.
• Select cryptographic algorithms.
• Authenticate each other by exchanging and validating digital certificates.
• Use asymmetric encryption techniques to generate a shared secret key,
which avoids the key distribution problem.
• SSL or TLS then uses the shared key for the symmetric encryption of
messages, which is faster than asymmetric encryption.

53

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
The TLS Handshake Protocol

54

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
The TLS Handshake Protocol

• The client sends a "Client hello" message to the server, along with the
client's random value and supported cipher suites.
• The server responds by sending a "Server hello" message to the client,
along with the server's random value.
• The server sends its certificate to the client for authentication and may
request a certificate from the client.
• The server sends the "Server hello done" message.
• If the server has requested a certificate from the client, the client sends it.
• The client creates a random Pre-Master Secret and encrypts it with
the public key from the server's certificate, sending the encrypted Pre-
Master Secret to the server.
55

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
The TLS Handshake Protocol

• The server and client each generate the Master Secret and session
keys based on the Pre-Master Secret.
• The client sends "Change cipher spec" notification to server to indicate that
the client will start using the new session keys for hashing and encrypting
messages. Client also sends "Client finished" message.
• Server receives "Change cipher spec" and switches its record layer security
state to symmetric encryption using the session keys.
• Server sends "Server finished" message to the client.
• Client and server can now exchange application data over the secured
channel they have established.
• All messages sent from client to server and from server to client are
encrypted using session key. 56

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
TLS Record Protocol

The Transport Layer Security (TLS) Record protocol secures application data
using the keys created during the Handshake.
The Record Protocol is responsible for securing application data and verifying
its integrity and origin.
Dividing outgoing messages into manageable blocks, and reassembling
incoming messages.
Compressing outgoing blocks and decompressing incoming blocks (optional).
Encrypting outgoing messages and decrypting incoming messages.
When the Record Protocol is complete, the outgoing encrypted data is passed
down to the Transmission Control Protocol (TCP) layer for transport.

57

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Problems with HTTPS

Mixed content occurs when initial HTML is loaded over a secure HTTPS
connection, but other resources (such as images, videos, stylesheets,
scripts) are loaded over an insecure HTTP connection.
Modern browsers display warnings about this type of content to indicate to the
user that this page contains insecure resources.
Invalid Certificates
Semantic attacks: Extended Validation Certificate

58

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Demos

HTTP and HTTPS Wireshark

Certificates in browser

Using Curl
curl is a tool to transfer data from or to a server, using one of the
supported protocols (HTTP, HTTPS, FTP, FTPS, SCP, SFTP, TFTP,
DICT, TELNET, LDAP or FILE).

59

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
DNS

The Domain Name System resolves the names of internet sites with their
underlying IP addresses.
A DNS server is a computer server that contains a database of public IP
addresses and their associated hostnames
DNS is a distributed database implemented in a hierarchy of name servers.
It is an application layer protocol for message exchange between clients and
servers.

60

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
DNS

DNS record – Domain name, ip address , validity, all the information related to
that domain name.
These records are stored in tree like structure.

61

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
DNS

A DNS cache (sometimes called a DNS resolver cache) is a temporary


database, maintained by a computer's operating system

The DNS cache attempts to speed up the process even more by handling the
name resolution of recently visited addresses before the request is sent out
to the internet

62

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Record Types

Address Mapping record (A Record)—also known as a DNS host record,


stores a hostname and its corresponding IPv4 address.
IP Version 6 Address record (AAAA Record)—stores a hostname and its
corresponding IPv6 address.
Canonical Name record (CNAME Record)—can be used to alias a hostname
to another hostname.
Mail exchanger record (MX Record)—specifies an SMTP email server for the
domain, used to route outgoing emails to an email server.
Reverse-lookup Pointer records (PTR Record)—allows a DNS resolver to
provide an IP address and receive a hostname (reverse DNS lookup).

63

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
CORS

Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional


HTTP headers to tell a browser to let a web application running at one origin
(domain) have permission to access selected resources from a server at a
different origin.
A web application makes a cross-origin HTTP request when it requests a
resource that has a different origin (domain, protocol, and port) than its own
origin.
For security reasons, browsers restrict cross-origin HTTP requests initiated from
within scripts.

64

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
The HTTP headers that relate to CORS

Request headers
Origin
Access-Control-Request-Method
Access-Control-Request-Headers
Response headers
Access-Control-Allow-Origin
Access-Control-Allow-Credentials
Access-Control-Expose-Headers
Access-Control-Max-Age
Access-Control-Allow-Methods
Access-Control-Allow-Headers 65

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
MIME

MIME types enable browsers to recognize the filetype of a file which has been
sent via HTTP by the webserver.
MIME (Multi-purpose Internet Mail Extensions) is an expansion of the original
Internet e-mail protocol that exchanges different kinds of data files on the
Internet: text, audio, video, images, application programs, and others.

66

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
MIME Types

text/html for normal web pages


text/plain for plain text
application/octet-stream meaning “download this file”
application/x-java-applet for Java™ applets
application/pdf for Adobe® PDF documents.

67

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Summary of Module 1

URL
HTTP
HTTP Methods
HTTP Request and Response
HTTPS
DNS

68

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Questions?

A) HTTP vs HTTPS?

69

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
References

1) Robert W. Sebesta, Programming the World Wide Web, 7th Ed, Pearson
2) Mozilla Developer Network

70

19/07/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
BITS Pilani
Hyderabad Campus

THANK YOU

71
19/07/2019
CSI ZG526 Web Technologies
I Sem 2018-19

BITS Pilani Akshaya Ganesan


BITS-Pilani
BITS Pilani
Hyderabad Campus

Lecture 2: HTML- Introduction


HTML Document Structure

An HTML document is composed of 3 parts:


1. a line containing HTML version information, e.g.:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
Note: <!DOCTYPE html> for HTML5
2. a declarative header section
– <head> tag
– The <title>tag is used to give the document a title
• normally displayed in the browser’s window title bar
3. a body containing the document's actual content
– Delimited with the <body> tag
After document type declaration, the remainder of an HTML document is contained by the html element

03/08/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
SAMPLE HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Basic HTML Document Layout</title>
</head>
<body>
<h1>My First Web Page</h1>
<hr>
<p>This is my <strong>first</strong> web page written in HTML.</p>
<h3>HTML</h3>
<p>HTML uses <em>markup tag</em> to <em>markup</em> a document.</p>
</body>
</html>

03/08/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
BASIC TAGS

Line breaks: <br>


Horizontal rules: <hr>
Headings
– Six sizes, 1 - 6, specified with <h1> to <h6>
• 1, 2, and 3 use font sizes that are larger than the default font size
• 4 uses the default size
• 5 and 6 use smaller font sizes
Blockquotes: <blockquote>
– To set a block of text off from the normal flow and appearance of text
Font Styles and Sizes (can be nested)
– Boldface: <b>
– Italics: <i>
– Smaller: <small> 5

03/08/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Links and Images

HTML links are defined with the <a> tag:


Example
<a href="https://www.bitspilani.com">This is a link to BITS website</a>

HTML Images
<img src=“BITS.jpg" alt=“BITS-pilani.com" width="104" height="142">

03/08/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
LISTS

The list is the content of the <ul> tag


List elements are the content of the <li> tag
<h3> Some Common Single-Engine Aircraft </h3>
<ul>
<li> Cessna Skyhawk </li>
<li> Beechcraft Bonanza </li>
<li> Piper Cherokee </li>
</ul>

03/08/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
HTML ATTRIBUTES

Attributes, in the form of name="value" pairs can be included in the opening tag to provide additional
information about the element.
Example 1: In <html lang="en">, the attribute lang="en" specifies the natural language for this document.
Example 2: In <meta charset="utf-8">, the attribute charset="utf-8" specifies the character encoding
scheme.
Example 3: An <img> (image) tag may contain these attributes:
<img src="logo.gif" alt="logo" width="50" height="30" />
The attribute "src" specifies the source-URL of the image; "alt" specifies an alternate text, if the image
cannot be displayed; "width" and "height" specify the width and height of the image displayed area.
Some of the attributes are mandatory (e.g., the "src" and "alt" attributes of the <img> tag); while some are
optional
Multiple attributes are separated by space, as follows:
<tag-name attName1="attValue1" attName2="attValue2" ...> ... </tag-name>
8

03/08/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Special Characters
Character Entity Reference
" &quot;
< &lt;
> &gt;
& &amp;
non-breaking space &nbsp;
→⇒↔⇔ &rarr; &rArr; &harr; &hArr;
° (degree) &deg;
©®€¢¥ &copy; &reg; &euro; &cent; &yen;
˜ &tilde;
×±∞ &times; &plusmn; &infin;
πΠσΣωΩ &pi; &Pi; &sigma; &Sigma; &omega; &Omega;
≥≤≡≈ &ge; &le; &equiv; &asymp;
⊂⊃⊆⊇∈ &sub; &sup; &sube; &supe; &isin;

03/08/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
TABLES

Tables
The basic unit of a table is a cell. Cells are grouped into row. Rows are grouped to form the table. This
corresponds well to the "row-centric" approach in the display.
<table>...</table>: contains the entire table.
<tr>...</tr>: contains a row.
<th>...</th> and <td>...</td>: contain a header cell and a data (detail) cell respectively.

<caption>...</caption>: specifies a caption.


<thead>...</thead>, <tbody>...</tbody>, and <tfoot>...</tfoot>: for marking out the table header, body
and footer.
<colgroup>...</colgroup> and <col>...</col>: for applying styles to column group and column
respectively.

10

03/08/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Tracking Document Changes

The del element is used to mark up text that has been deleted from a
document. It is useful if you want the original text to remain to provide a
record of changes to the document over time.

There are two attributes that can be used to provide additional information
about the reason a change was made to a document.

cite can be used to add a URL that further explains the reason for the change.
datetime can be used to specify the time when the change was made.

11

03/08/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
The <form> tag
The <form arguments> ... </form> tag encloses form elements (and probably other HTML as well)
– action="url" (required)
• Specifies where to send the data when the Submit button is clicked
– method="get" (default)
• Form data is sent as a URL with ?form_data info appended to the end
• Can be used only if data is all ASCII and not more than 100 characters
– method="post"
• Form data is sent in the body of the URL request
• Cannot be bookmarked by most browsers
– target="target"
• Tells where to open the page sent as a result of the request
• target= _blank means open in a new window
• target= _top means use the same window

12

03/08/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
The <input> tag

Most, but not all, form elements use the input tag, with a type="..." argument to
tell which kind of element it is
– type can be text, checkbox, radio, password, hidden, submit, reset, button, file, or
image
Other common input tag arguments include:
– name: the name of the element
– value: the “value” of the element; used in different ways for different values of type
– readonly: the value cannot be changed
– disabled: the user can’t do anything with this element
– Other arguments are defined for the input tag but have meaning only for certain values of
type

13

03/08/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
A complete example

<html>
<head>
<title>Get Identity</title>
<meta http-equiv="Content-Type" content="text/html;
charset=iso-8859-1">
</head>
<body>
<p><b>Who are you?</b></p>
<form method="post" action="">
<p>Name:
<input type="text" name="textfield">
</p>
<p>Gender:
<input type="radio" name="gender" value="m">Male
<input type="radio" name="gender" value="f">Female</p>
</form>
</body>
</html> 14

03/08/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
New HTML5 input Types

<input type="email"> (HTML5) Email Address Can be validated.


<input type="url"> (HTML5) URL Can be Validated.
<input type="number"> (HTML5) Numeric value You can use attributes min|max to specify
the min and max values; and step to
specify the step size (default of 1).
Many browsers add a spin button (with
up/down arrow) to the right corner of the
box
<input type="range"> (HTML5) Numeric value You can use attribute min|max to specify
the min and max values.
Many browsers use a slider for range.
<input type="color"> (HTML5) Color Browser may pop-up a color chooser.
<input Date and Time Browser may provide a drop-down
type="date|time|datetime|month|week"> calendar. Poorly supported now.
(HTML5)
<input type="tel"> (HTML5) Phone number No validation as phone numbers vary
across countries.
<input type="search"> (HTML5) Search keywords Search Box for entering search keywords.
15
No validation.
03/08/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
HTML5 New Semantic Elements

Many web sites contain HTML code like: <div id="nav"> <div class="header"> <div id="footer">
to indicate navigation, header, and footer.
HTML5 offers new semantic elements to define different parts of a web page:
<article>
<aside>
<details>
<figcaption>
<figure>
<footer>
<header>
<main>
<mark>
<nav>
<section>
<summary> 16
<time> CSIZG526 Web Technologies
03/08/2019 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Metadata: the <meta> element

• Metadata is data (information) about data.


• The <meta> tag provides metadata about the HTML document. Metadata will
not be displayed on the page, but will be machine parsable.
• Meta elements are typically used to specify page description, keywords,
author of the document, last modified, and other metadata.
• The metadata can be used by browsers (how to display content or reload
page), search engines (keywords), or other web services.
• HTML5 introduced a method to let web designers take control over the
viewport (the user's visible area of a web page), through the <meta> tag

17

03/08/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Viewport attribute for meta element

• You should include the following <meta> viewport element in all your web
pages:
• <meta name="viewport" content="width=device-width, initial-scale=1.0">
• A <meta> viewport element gives the browser instructions on how to control
the page's dimensions and scaling.
• The width=device-width part sets the width of the page to follow the screen-
width of the device (which will vary depending on the device).
• The initial-scale=1.0 part sets the initial zoom level when the page is first
loaded by the browser.

18

03/08/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
.

HTML5 Attributes

Attribute Value Description


charset character_set Specifies the character encoding for the HTML document

content text Gives the value associated with the http-equiv or name attribute

http-equiv content-type Provides an HTTP header for the information/value of the content
default-style attribute
refresh
name application-name Specifies a name for the metadata
author
description
keywords
viewport

19

03/08/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Examples

Example 1 - Define keywords for search engines:


<meta name="keywords" content="HTML, CSS, XML, XHTML, JavaScript">
Example 2 - Define a description of your web page:
<meta name="description" content="Free Web tutorials on HTML and CSS">
Example 3 - Define the author of a page:
<meta name="author" content="John Doe">
Example 4 - Refresh document every 30 seconds:
<meta http-equiv="refresh" content="30">

20

03/08/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Other type of Meta Element

For example, Open Graph Data is a metadata protocol that Facebook invented to provide richer
metadata for websites. In the MDN sourcecode, you'll find this:
<meta property="og:image" content="https://developer.cdn.mozilla.net/static/img/opengraph-
logo.dc4e08e2f6af.png">
<meta property="og:description" content="The Mozilla Developer Network (MDN) provides
information about Open Web technologies including HTML, CSS, and APIs for both Web sites
and HTML5 Apps. It also documents Mozilla products, like Firefox OS.">
<meta property="og:title" content="Mozilla Developer Network">
One effect of this is that when you link to MDN on facebook, the link appears along with an
image and description: a richer experience for users.

21

03/08/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
DIV and SPAN

• The <div> tag defines a division or a section in an HTML document.


• The <div> element is often used as a container for other HTML elements to style them with CSS or to
perform certain tasks with JavaScript.
• <div style="color:#0000FF">
<h3>This is a heading</h3>
<p>This is a paragraph.</p>
</div>

• The <span> tag is used to group inline-elements in a document.


• The <span> tag provides no visual change by itself.
• The <span> tag provides a way to add a hook to a part of a text or a part of a document.
• A <span> element used to color a part of a text:
• <p>My mother has <span style="color:blue">blue</span> eyes.</p>

22

03/08/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
The <video> element

The <video> element allows you to embed a video very easily.


<video src="rabbit320.webm" controls>
<p>Your browser doesn't support HTML5 video. Here is a <a
href="rabbit320.webm">link to the video</a> instead.</p>
</video>
The features of note are:
src
controls
– Users must be able to control video and audio playback

The paragraph inside the <video> tags

23

03/08/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
The Video elemet

Other features are:


width and height
autoplay
loop
muted
poster
This attribute takes as its value the URL of an image, which will be displayed before the video is played. It is
intended to be used for a splash or advertising screen.

preload
this attribute is used in the element for buffering large files. It can take one of 3 values:
– "none" does not buffer the file
– "auto" buffers the media file
– "metadata" buffers only the metadata for the file
24

03/08/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
The <audio> element

The <audio> element works in exactly the same way as the <video> element
<audio controls>
<source src="viper.mp3" type="audio/mp3">
<source src="viper.ogg" type="audio/ogg">
<p>Your browser doesn't support HTML5 audio. Here is a <a href="viper.mp3">link to the
audio</a> instead.</p>
</audio>

The <audio> element doesn't support the width/height attributes


It also doesn't support the poster attribute — again, no visual component.
25

03/08/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
The <track> element

HTML5 allows us to specify subtitles for a video using the <track> element.
Web Video Text Tracks Format (WebVTT) is a format for displaying timed text tracks (such as
subtitles or captions) using the <track> element.
The primary purpose of WebVTT files is to add text overlays to a <video>.
WebVTT is a text based format, which must be encoded using UTF-8.
<video id="video" controls preload="metadata">
<source src="video/sintel-short.mp4" type="video/mp4">
<source src="video/sintel-short.webm" type="video/webm">
<track label="English" kind="subtitles" srclang="en" src="captions/vtt/sintel-en.vtt" default>
<track label="Deutsch" kind="subtitles" srclang="de" src="captions/vtt/sintel-de.vtt">
<track label="Español" kind="subtitles" srclang="es" src="captions/vtt/sintel-es.vtt">
</video>

26

03/08/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Inline frame

The <iframe> creates an inline frame, which embeds an independent HTML


document into the current document
<iframe width="420" height="315"
src="https://www.youtube.com/embed/tgbNymZ7vqY?playlist=tgbNymZ7vqY
&loop=1">
</iframe>
Embed Youtube videos to HTML
YouTube <object> and <embed> were deprecated from January 2015. You
should migrate your videos to use <iframe> instead.

27

03/08/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Figure Element

HTML5 <figure> and <figcaption> Elements


The purpose of a figure caption is to add a visual explanation to an image.
In HTML5, an image and a caption can be grouped together in
a <figure> element:
<figure>
<img src=“Logo.jpg" alt="The Pulpit Rock" width="304" height="228">
<figcaption>Fig1. - The Pulpit Rock, Norway.</figcaption>
</figure>

28

03/08/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
HTML Graphics

HTML5 SVG
SVG stands for Scalable Vector Graphics
SVG is used to define graphics for the Web
The HTML <svg> element is a container for SVG graphics.
SVG has several methods for drawing paths, boxes, circles, text, and graphic images.
HTML Canvas
The HTML <canvas> element is used to draw graphics, on the fly, via JavaScript.
The <canvas> element is only a container for graphics. You must use JavaScript to actually
draw the graphics.
Canvas has several methods for drawing paths, boxes, circles, text, and adding images.

29

03/08/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Difference between Canvas and SVG

Canvas SVG

•Resolution dependent •Resolution independent


•No support for event handlers •Support for event handlers
•Poor text rendering capabilities •Best suited for applications with large rendering areas
•You can save the resulting image as .png or .jpg (Google Maps)
•Well suited for graphic-intensive games •Slow rendering if complex (anything that uses the DOM
a lot will be slow)
•Not suited for game applications

30

03/08/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
HTML and debugging

• HTML is not compiled into a different form before the browser parses it and shows the result
(it is interpreted, not compiled).
• The way that browsers parse HTML is a lot more permissive than how programming
languages are run
• There are two main types of error
• Syntax errors: These are spelling errors in your code that actually cause the program not to
run. Logic errors: These are errors where the syntax is actually correct, but the code is not
what you intended.
• HTML itself doesn't suffer from syntax errors because browsers parse it permissively,
meaning that the page still displays even if there are syntax errors.

• Browsers are intelligent and use inspect element

31

03/08/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Some new Features of HTML5

• Geolocation
– Get user position, GPS

• WebStorage
– Instead of cookies

• Indexed DB
• Web Workers
– : Certain web applications use heavy scripts to perform functions. Web Workers use separate background
threads for processing and it does not effect the performance of a web page.

• Server Sent Reponses

32

03/08/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
HTML Boilerplate

• The underlying foundations of the vast majority of websites are very similar.
• Boilerplates are similar to templates,
• They contain text and graphics to start you off rather than just layouts for
these elements.
• An HTML boilerplate is a set of files that you can download, which provide a
foundation for any website you create.
• Boilerplates may contain a range of file types, including HTML documents,
but also add CSS, JavaScript, placeholder images
• HTML5 Boilerpate is the self-described "web's most popular front-end
template
• Alternatives: Bootstrap, Web Starter Kit and Skeleton
• WIX, Wordpress etc., 33

03/08/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Q&A

What happens if you view a new HTML5 form input type in an older browser?
Which is the most accurate way for Geolocation to get a user’s position?
Which HTML5 element/tag would you use to define a footer?

Which of these did we not use and are no longer valid in HTML5?

Frame
Embed
Align
div
34

03/08/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
BITS Pilani
Hyderabad Campus

Thank You
CSI ZG526 Web Technologies
I Sem 2019-20

BITS Pilani Akshaya Ganesan


BITS-Pilani
BITS Pilani
Hyderabad Campus

Module 3: CSS

2
What is CSS

Cascading Style Sheets


Web browsers apply CSS rules to a document to affect how they are displayed.

A CSS rule is formed from:


– A set of properties, which have values set to update how the HTML content is displayed,
For example
I want my element's width to be 50% of its parent element, and its background to be red.
– A selector, which selects the element(s) you want to apply the updated property values to.
For example,
I want to apply my CSS rule to all the paragraphs in my HTML document.

A set of CSS rules contained within a stylesheet determines how a webpage


should look.
3

10/02/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
An CSS example

<!DOCTYPE html> style.css


<html> h1 {
<head> color: blue;
<meta charset="utf-8"> background-color: yellow;
<title>My CSS experiment</title> border: 1px solid black;
<link rel="stylesheet" href="style.css"> }
</head>
<body> p{
<h1>Hello World!</h1> color: red;
<p>This is my first CSS example</p> }
</body>
</html>

10/02/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
How does CSS actually work?

When a browser displays a document, it must combine the document's content with its style
information. It processes the document in two stages:
1. The browser converts HTML and CSS into the DOM (Document Object Model). The DOM
represents the document in the computer's memory. It combines the document's content
with its style.
2. The browser displays the contents of the DOM.

10/02/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Document Object Model (DOM)

A DOM has a tree-like structure.


Each element, attribute and piece of text in the markup language becomes
a DOM node
The nodes are defined by their relationship to other DOM nodes. S
Some elements are parents of child nodes, and child nodes have siblings.
DOM Structure <p>
P Let's use: span {
├─ "Let's use:" <span>Cascading</span> border: 1px solid black;
├─ SPAN <span>Style</span> background-color: lime;
| └─ "Cascading" <span>Sheets</span> }
├─ SPAN </p>
| └─ "Style"
└─ SPAN
6
| └─ "Sheets"
10/02/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Applying CSS to HTML

There are three different ways to apply CSS to an HTML document


1. External StyleSheet
2. Internal StyleSheet
3. Inline Styles

10/02/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
External StyleSheet

An external stylesheet is when you have your CSS written in a separate file with
a .css extension,
Reference it from an HTML <link> element.

<link rel="stylesheet" href="style.css">

One stylesheet to style multiple documents


Updation and modification would be easy

10/02/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Internal StyleSheet

An internal stylesheet is place your CSS inside a <style> element, contained inside the HTML
head.
<html>
<head>
<title>My CSS experiment</title>
<style>
h1 {
color: blue;
background-color: yellow;
}
p {
color: red;
}
</style>
</head>
<body>
<h1>Hello World!</h1>
<p>This is my first CSS example</p>
9
</body>
</html>
10/02/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Inline styles

Inline styles are CSS declarations that affect one element only, contained within a style attribute
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My CSS experiment</title>
</head>
<body>
<h1 style="color: blue;background-color: yellow;border: 1px solid black;">Hello World!</h1>
<p style="color:red;">This is my first CSS example</p>
</body>
</html>
Used in very restrictive environments
10

10/02/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
CSS Syntax

CSS consists of two building blocks:


Properties: Human-readable identifiers that indicate which stylistic features (e.g. font, width,
background color) .
Values: Each specified property is given a value, which indicates how you want to change those
stylistic features (e.g. what you want to change in the font, width or background color to.)
A property paired with a value is called a CSS declaration.
CSS declarations are put within CSS Declaration Blocks.
CSS declaration blocks are paired with selectors to produce CSS Rulesets (or CSS Rules).
Both properties and values are case-sensitive in CSS
The property and value in each pair is separated by a colon (:).

11

10/02/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
CSS Declarations

background-color: yellow;

There are more than 300 different properties in CSS and nearly an
infinite number of different values.
Not all pairs of properties and values are allowed; each property has a specific
list of valid values defined for it.
If a property is unknown or if a value is not valid for a given property, the
declaration is invalid and is ignored by the browser.
NOTE:
In CSS (and other web standards), US spelling has been agreed on as the
standard to stick to where uncertainty arises. For example, color (as seen in the
above code) should always be spelt color. colour won't work. 12

10/02/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
CSS declaration blocks

Declarations are grouped in blocks, with each set of declarations being


wrapped by an opening curly brace, ({) and a closing one (}).

Each declaration contained inside a declaration block has to be separated by a


semi-colon (;)

{
colour: blue;
background-color: yellow;
border: 1px solid black;
}

13

10/02/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
CSS selectors and rules

How to tell our declaration blocks which elements they should be applied to?
• This is done by prefixing each declaration block with a selector —
• A pattern that matches some elements on the page. The associated declarations will be
applied to those elements only.
• The selector plus the declaration block is called a ruleset, or often simply just a rule.
• A rule match multiple elements by including multiple selectors separated by commas (a
group,) and selectors can be chained
h1 , h2, p{
colour: blue;
background-color: yellow;
border: 1px solid black;
}

14

10/02/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
COLORS

• Colors are specified using predefined color names, or RGB, HEX, HSL,
RGBA, HSLA values.
• RGB Colors
• RGB color values are supported in all browsers.
• An RGB color value is specified with: rgb(red, green, blue).
• Each parameter (red, green, and blue) defines the intensity of the color as an
integer between 0 and 255.
• For example, rgb(0, 0, 255) is rendered as blue, because the blue parameter
is set to its highest value (255) and the others are set to 0.
• background-color: rgb(0, 191, 255);

15

10/02/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
COLORS

• Hexadecimal Colors
• Hexadecimal color values are also supported in all browsers.
• A hexadecimal color is specified with: #RRGGBB.
• RR (red), GG (green) and BB (blue) are hexadecimal integers between 00
and FF specifying the intensity of the color.
• For example, #0000FF is displayed as blue, because the blue component is
set to its highest value (FF) and the others are set to 00.

16

10/02/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
COLORS

• HSL stands for hue, saturation, and lightness.


• HSL color values are specified with: hsl(hue, saturation, lightness).
• Hue
• Hue is a degree on the color wheel from 0 to 360. 0 is red, 120 is green, 240 is blue.

• Saturation
• Saturation is a percentage value; 0% means a shade of gray and 100% is the full color.

• Lightness
• Lightness is also a percentage; 0% is black, 100% is white.
• background-color: hsl(180, 50%, 50%);

• HWB (Hue, Whiteness, Blackness) is a suggested standard for CSS4.

17

10/02/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
COLORS

• RGBA and HSLA


• RGB and HSL both have corresponding modes — RGBA and HSLA — that
allow you to set not only what color you want to display, but also what
transparency you want that color to have. Their corresponding functions take
the same parameters, plus a fourth value in the range 0–1 — which sets the
transparency, or alpha channel. 0 is completely transparent, and 1 is
completely opaque.
• Opacity
• There is another way to specify transparency via CSS — the opacity
property. Instead of setting the transparency of a particular color, this sets the
transparency of all selected elements and their children.
• opacity: 0.5;
18

10/02/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Font Properties
font-family
– Value is a list of font names - browser uses the first in the list it has
font-size
– Possible values: a length number or a name, such as smaller, xx-large, etc.
font-style
– italic, oblique (useless), normal
font-weight - degrees of boldness
– bolder, lighter, bold, normal
font - for specifying a list of font properties
– font: bolder 14pt Arial Helvetica
– Order must be: style, weight, size, font name(s)

19

10/02/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
List Properties

On unordered lists list-style-type can be used to specify the shape of the


bullets
– disc (default), square, or circle
– Set it on either the <ul> or <li> tag
<h3> Fruit </h3>
<ul>
<li style = "list-style-type: disc"> Apple </li>
<li style = "list-style-type: square"> Orange </li>
<li style = "list-style-type: circle"> Pear </li>
</ul>
On ordered lists list-style-type can be used to change the sequence
values

20

10/02/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Background Images

The background-image property


background-repeat property
– Possible values: repeat (default), no-repeat, repeat-x, or repeat-y
background-position property
– Possible values: top, center, bottom, left, or right

21

10/02/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
BITS Pilani
Hyderabad Campus

Thank You
CSI ZG526 Web Technologies
I Sem 2019-20

BITS Pilani Akshaya Ganesan


BITS-Pilani
BITS Pilani
Hyderabad Campus

Module 3: CSS- BOX model

2
What is the Box Model?
The box model is a tool we use to understand how our content
will be displayed on a web page.
Each HTML element appearing on our page takes up a "box" or
"container" of space.
Each box size is affected not only by content but also by padding,
borders, and margins.
By knowing how to calculate the dimensions of each box, we can
accurately predict how elements will lay out on the screen.
As we build a new page, we can arrange these boxes on the screen,
creating a balanced layout with white space around the content.

The importance of the box model concept cannot be


overemphasized. It would be difficult and frustrating to create a
website without understanding thisTechnologies
CSI ZG526 Web concept.
Box Model

10/02/2019 CSI ZG526 Web Technologies 4


Introducing the <div> Element
The <div> ("division") element groups other elements on the
screen.
By setting the width and height attributes via CSS, we can reserve
a precise amount of space on our page for specific content.
The actual content is nested and contained within the opening <div>
and closing </div> tags.
When we apply CSS styling directly to the <div> element, all the
elements contained within that <div> will inherit that style.
By using multiple <div> elements as building blocks, we can design
an entire web page layout.

CSI ZG526 Web Technologies


Example <div> Element
Let's create a box on the screen and add a border around it:
<style type="text/css">
.box200 {
width: 200px;
height: 200px;
border: 1px solid black;
color: blue;
}
</style>
...
This is before the box.
<div class="box200">
This is a 200 by 200 pixel box with
a 1px border.
</div>
This is after the box.
...
With the border set, we
Notice that there is almost no space separating the text from the box border. Elements such as can see the exact space
paragraphs, headers, and lists automatically insert padding and margins, but plain text does not
do so. taken up on the page.
CSI ZG526 Web Technologies
Adding Padding and Margin
Let's create some space between elements by adding both padding and margin:

<style type="text/css">
.box200 {
width: 200px;
height: 200px;
border: 1px solid black;
color: blue;
padding: 10px;
margin: 10px;
}
</style>
...

The 10 pixel padding adds buffer space, on all four sides, between the
content and border. The 10 pixel margin adds buffer space, on all four
sides, between the border and surrounding elements.
CSI ZG526 Web Technologies
Padding and Margin Illustrated
The dotted red line
shows the margin's
outer boundary and the
dotted green line
shows the padding's
inner boundary.
242px When we define the
high width and height of a
<div> element, these
dimensions apply only
to the actual content,
not to the padding,
border, or margin.
242px CSI ZG526 Web Technologies
wide
Calculating Total Dimensions
When we are planning our page, we have to calculate exactly how much screen
space a <div> or any other element will use. The formula is:
Total element width = defined width + left padding + right padding + left
border + right border + left margin + right margin.
Total element height = defined height + top padding + bottom padding + top
border + bottom border + top margin + bottom margin.

In our previous example:


Total <div> width = 200px + 10px + 10px + 1px + 1px + 10px + 10px = 242px.
Total <div> height = 200px + 10px + 10px + 1px + 1px + 10px + 10px = 242px.

CSI ZG526 Web Technologies


Setting Individual Margins
We can set the specific margin sizes by using these four properties:
margin-top:
margin-right:
margin-bottom:
margin-left:

margin:10px; Sets all four margins to be 10px.

margin: 10px Sets the top and bottom margins as 10px


5px; and the left and right margins as 5px.
Sets the top margin as 20px, the right
margin: 20px 10px 5px 15px; margin as 10px, the bottom margin as 5px,
and the left margin as 15px.
CSI ZG526 Web Technologies
Setting Individual Padding
We can set specific padding sizes by using these four properties:
padding-top:
padding-ight:
padding-bottom:
padding-left:

padding: 5px; Sets padding as 5px on all four


sides.
Sets top and bottom padding as 25px
padding: 25px 5px;
and left and right padding as 5px.
Sets top padding as 50px, right padding
padding: 50px 10px 15px 5px; as 10px, bottom padding as 15px, and
the left padding as 5px.
CSI ZG526 Web Technologies
Setting Individual Borders
Customizing borders is more involved. Since they are visible on the page, we
have to specify style, thickness, and color. Accordingly, there are more
properties available:
border-top-width: border-top-style: border-top-color:
border-right-width: border-right-style: border-right-color:
border-bottom-width: border-bottom-style: border-bottom-color:
border-left-width: border-left-style: border-left-color:

To make things easier, we can use the shorthand method as before:


border-width: 10px;
border-style: solid dashed;
border-color: blue red orange gray;

If the three border properties will be identical on all four sides, we can use a
single-line border shorthand, as we did in an earlier lesson:
border: 5px solid blue;

CSI ZG526 Web Technologies


Example of Customized Settings
Here we have set custom padding, borders, and margins:

<style type="text/css">
.box200 {
width: 200px;
height: 200px;
color: blue;
padding: 40px 10px 0px 10px;
margin: 25px 5px;
border-width: 2px 5px;
border-style: solid dotted;
border-color: red blue green maroon;
}
</style>

CSI ZG526 Web Technologies


CSS Syntax:
Selector Strings
Single element type:

Multiple element types:

All element types:

Specific elements by id:

CSI ZG526 Web Technologies


CSS Syntax:
Selector Strings
Elements belonging to a style class:

– Referencing a style class in HTML:

Elements of a certain type and class: class selector: begins with a


period .

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides


CSI ZG526 Web Technologies
CSS Syntax:
Selector Strings
Elements belonging to a style class:

– Referencing a style class in HTML:

Elements of a certain type and class:

this span belongs to three style classes

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides


CSI ZG526 Web Technologies
CSS Syntax:
Selector Strings
Elements belonging to a style class:

– Referencing a style class in HTML:

Elements of a certain type and class:

this rule applies only to span’s belonging to class special

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides


CSI ZG526 Web Technologies
CSS Syntax:
Selector Strings
Source anchor elements: pseudo-classes

Element types that are descendents:

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides


CSI ZG526 Web Technologies
CSS Syntax:
Selector Strings
Source anchor elements:

Element types that are descendants:

rule applies to li element that is

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides


CSI ZG526 Web Technologies
CSS Units
Pixels (px) are referred to as absolute units because they will always be the same size regardless of any other related
settings.
Other absolute units are as follows:
mm, cm, in: Millimeters, centimeters, or inches.
pt, pc: Points (1/72 of an inch) or picas (12 points.)

Relative units, which are relative to the current element's font-size:


em: 1em is the same as the font-size of the current element .
Percentage: Font:50%
In this case, the parent font-size is 16px — the page default, so the computed value will be 50% of this, or 8px.

Boxes whose width will always shift to be a certain percentage of their parent container's width

20

16/02/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
CSS Font Properties
All CSS length values except 0 need units

CSI ZG526 Web Technologies


CSS Font Properties

Computed value
of font-size
property

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides


CSI ZG526 Web Technologies
CSS Font Properties

Reference font defines em and ex units


– Normally, reference font is the font of the element being styled
– Exception: Using em/ex to specify value for font-size

parent element’s font is


reference font
CSI ZG526 Web Technologies
CSS Font Properties
Other ways to specify value for
font-size:
– Percentage (of parent font-size)

– Absolute size keyword: xx-small, x-small, small, medium (initial value), large,
x-large, xx-large
• User agent specific; should differ by ~ 20%
– Relative size keyword: smaller, larger
• Relative to parent element’s font

CSI ZG526 Web Technologies


CSS Font Properties
font shortcut property:

CSI ZG526 Web Technologies


CSS Text Formatting

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson’s slides


Positioning

• The positioning of elements on a webpage is very fluid.


• The position property specifies the type of positioning method used for an
element (static, relative, fixed, absolute or sticky).

27

16/02/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Positioning

• Position: static
• Position: relative
– By default, if you set the position property to relative, the element is placed as if it were static, but you can then
use the top, bottom, left and right property to move it around by setting these values relative to the original
position of element.

• Position: absolute
– An absolute positioned element is placed exactly where you want it to within the browser window, by adjusting
the top, bottom, left and/or right properties. This means that you can place elements e.g. in the top, right corner,
even if your main page has been tied to the middle of the screen.

• Position: fixed
– By using the fixed property, your element will be positioned as if it were absolute, with one very important
addition: When the user scrolls, the fixed element will remain in this position all the time. This allows you to
create, for instance, a top menu which remains on screen even when the user scrolls through down through
your page.

28

16/02/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
The cascade

CSS is an acronym of Cascading Style Sheets.


At its most basic level it indicates that the order of CSS rules matter.
Which selectors win out in the cascade depends on three factors

• Importance
• Specificity
• Source order

29

16/02/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Importance

• In CSS, the declaration which will always win over all others:
• !important.
• Conflicting declarations will be applied in the following order,
• The later ones overriding earlier ones.
• Declarations in user agent style sheets
• Normal declarations in user style sheets
• Normal declarations in author style sheets
• Important declarations in author style sheets
• Important declarations in user style sheets

30

16/02/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Specificity

• Specificity is a measure of how specific is a selector


• how many elements it could match.
• Element selectors have low specificity.
• Class selectors have a higher specificity, so will win against element selectors.
• ID selectors have an even higher specificity, so will win against class selectors.
• The only way to win against an ID selector is to use !important.

31

16/02/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Specificity

The amount of specificity a selector has is measured using four different values.
thousands, hundreds, tens and ones — four single digits in four columns:

Thousands: Score one in this column if the declaration is inside a style attribute
– (such declarations don't have selectors, so their specificity is always simply 1000.) Otherwise 0.

Hundreds: Score one in this column for each ID selector contained inside the
overall selector.
Tens: Score one in this column for each class selector, attribute selector, or
pseudo-class contained inside the overall selector.
Ones: Score one in this column for each element selector or pseudo-element
contained inside the overall selector.
32

16/02/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Specificity

Selector Thousands Hundreds Tens Ones Total specificity


h1 0 0 0 1 0001
#important 0 1 0 0 0100
h1 + p::first-letter 0 0 0 3 0003
li > a[href*="en-US"] > .inline-warning 0 0 2 2 0022
#important div > div > a:hover, 1 1 1 3 1113
(inside an element's style attribute)

33

16/02/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Source order

As mentioned above, if multiple competing selectors have the same importance


and specificity, the third factor that comes into play to help decide which rule
wins is source order.
later rules will win over earlier rules. Whereas in this example the first rule wins because source order is
overruled by specificity:
For example:
p{ /* This rule will win */
.footnote {
color: blue; color: blue;
}
}
/* This rule will win over the first one */ p {
color: red;
p{ }
color: red;
34
}
16/02/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Rule Mixing

When several CSS rules match the same element, they are all applied to that element. Only
after that are any conflicting properties evaluated to see which individual styles will win over
others.
<p>I'm <strong>important</strong></p>
/* specificity: 0002 */ I'm important
p strong {
background-color: khaki;
color: green;
}
/* specificity: 0001 */
strong {
text-decoration: underline;
color: red;
} 35

16/02/2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
BITS Pilani
Hyderabad Campus

Thank You
CSI ZG526 Web Technologies
II Sem 2018-19

BITS Pilani Akshaya Ganesan


BITS-Pilani
BITS Pilani
Hyderabad Campus

Lecture 6: Javascript

2
Client Side Scripting

CS380

CSI ZG526 Web Technologies 3


Why use client-side programming?
PHP already allows us to create dynamic web pages. Why also use client-side
scripting?
client-side scripting (JavaScript) benefits:
– usability: can modify a page without having to post back to the server (faster UI)
– efficiency: can make small, quick changes to page without waiting for server
– event-driven: can respond to user actions like clicks and key presses

CS380

CSI ZG526 Web Technologies 4


Why use client-side programming?
server-side programming (PHP) benefits:
– security: has access to server's private data; client can't see source code
– compatibility: not subject to browser compatibility issues
– power: can write files, open connections to servers, connect to databases, ...

CS380

CSI ZG526 Web Technologies 5


What is Javascript?
a lightweight programming language ("scripting language")
– used to make web pages interactive
– insert dynamic text into HTML (ex: user name)
– react to events (ex: page load user click)
– get information about a user's computer (ex: browser type)
– perform calculations on user's computer (ex: form validation)

JavaScript is a scripting language.


• Allows you to implement complex tasks on web pages
• Displaying timely content updates, or interactive maps, or animated 2D/3D graphics, or scrolling video
jukeboxes, etc.
• It is the third layer of standard web technologies, two of which (HTML and CSS)
JavaScript scripts are executed entirely by the browser.
– The JavaScript is executed by the browser's JavaScript engine, after the HTML and CSS have been assembled
and put together into a web page.
– Makes the Web pages more interactive

CS380

CSI ZG526 Web Technologies 6


JavaScript

JavaScript is dynamically/weakly typed.


It is faster and easier than other programming languages.
It is an interpreted Language
Platform independent
Initially only implemented client-side in web browsers
JavaScript engines are now embedded on server-side in web servers and databases, and in non-web programs such as
word processors and PDF software etc.,

USES OF JAVASCRIPT
– Transfer of some load from server to client
– User interactions through forms
– Events easily detected with JavaScript
– Create web pages , add content to web pages

17/02/2019 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Origins of JavaScript

• Originally developed by Netscape, as LiveScript


• Became a joint venture of Netscape and Sun in 1995, renamed JavaScript
• Now standardized by the European Computer Manufacturers Association as
ECMA-262
• An HTML-embedded scripting language
• Collections of JavaScript code is called scripts, not programs

17/02/2019 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
JavaScript and Java

• JavaScript and Java are only related through syntax


• JavaScript is dynamically typed
• JavaScript’s support for objects is very different
• JavaScript is interpreted
– Source code is embedded inside HTML doc, there is no compilation
• JavaScript objects are collections of properties, which are like the members of classes in
Java
– Data and method properties
• JavaScript has primitives for simple types

17/02/2019 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
JavaScript Execution

• When you load a web page in your browser, you are running your code (the
HTML, CSS, and JavaScript) inside an execution environment (the browser
tab).
• The JavaScript is executed by the browser's JavaScript engine, after the
HTML and CSS have been assembled and put together into a web page.
• This ensures that the structure and style of the page are already in place by
the time the JavaScript starts to run.

10

17/02/2019 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
JavaScript Execution

• Example (Inline)
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can change HTML content.</p>
<button type="button" onclick='document.getElementById("demo").innerHTML = "Hello JavaScript!"'>Click
Me!</button>
</body>
</html>

11

17/02/2019 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Adding JS(Internal)

• Old JavaScript examples may use a type attribute: <script


type="text/javascript">.
• The type attribute is not required. JavaScript is the default scripting language
in HTML.
• A JavaScript function is a block of JavaScript code, that can be executed
when "called" for.
• For example, a function can be called when an event occurs, like when the
user clicks a button.
• You can place any number of scripts in an HTML document.
• Scripts can be placed in the <body>, or in the <head> section of an HTML
page, or in both.
12

17/02/2019 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
External Script

• Scripts can also be placed in external files:


• function myFunction() {
• document.getElementById("demo").innerHTML = "Paragraph changed.";
• }
• External scripts are practical when the same code is used in many different web pages.
• JavaScript files have the file extension .js.
• To use an external script, put the name of the script file in the src (source) attribute of a
<script> tag:

• Example
• <script src="myScript.js"></script>
• You can place an external script reference in <head> or <body>

13

17/02/2019 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Embedding in HTML docs

Either directly, as in
<script type = “text/javascript”>
-- JavaScript script –
</script>
Or indirectly, as a file specified in the src attribute of <script>, as in
<script type = “text/javascript”
src = “myScript.js”>
</script>

14

17/02/2019 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Event-driven programming

split breaks apart a string into an array using a


delimiter
can also be used with regular expressions (seen later)
join merges an array into a single string, placing a
delimiter between them

CSI ZG526 Web Technologies 15


A JavaScript statement: alert
a JS command that pops up a dialog box with a message

alert("IE6 detected. Suck-mode enabled.");

JS

CSI ZG526 Web Technologies 16


Event-driven programming

you are used to programs start with a main method


(or implicit main like in PHP)
JavaScript programs instead wait for user actions
called events and respond to them
event-driven programming: writing programs
driven by user events

CSI ZG526 Web Technologies 17


Buttons
button's text appears inside tag; can also contain images
To make a responsive button or other UI control:
1. choose the control (e.g. button) and event (e.g. mouse 1. click) of interest
2. write a JavaScript function to run when the event occurs
3. attach the function to the event on the control

<button>Click me!</button>
HTML

CS380

CSI ZG526 Web Technologies 18


JavaScript functions
function name() {
statement ; the above could be the contents of
statement ; example.js linked to our HTML
... page
statement ;
}
statements placed into functions
JS can be evaluated in response to
user events
function myFunction() {
alert("Hello!");
alert("How are you?");
}
JS
CS380

CSI ZG526 Web Technologies 19


Event handlers
JavaScript functions can be set as event handlers
– when you interact with the element, the function will execute
onclick is just one of many event HTML attributes we'll use
but popping up an alert window is disruptive and annoying
– A better user experience would be to have the message appear on the
page...

<element attributes
onclick="function();">...
HTML
<button onclick="myFunction();">Click
me!</button>
CS380
HTML
CSI ZG526 Web Technologies 20
JavaScript Running Order

When the browser encounters a block of JavaScript, it generally runs it in order,


from top to bottom.
var para = document.querySelector('p');
para.addEventListener('click', updateName);

If you swapped the order of the first two lines of code, it would no longer work.
An error returned in the browser developer console

21

17/02/2019 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Variables

A variable is a container for a value


JavaScript is dynamically typed
var sum = 12;
let x=20;
Intializing a variable myName = 'Chris'; myAge = 37;
Updating a variable: change (or update) that value by simply giving it a different value.
Variables declared const cannot be changed const x=30;
Variable naming rules
Characters (0-9, a-z, A-Z) and the underscore character, Don't use underscores at the start of variable
name
Variables are case sensitive — so myage is a different variable to myAge.
Avoid using JavaScript reserved words as your variable names

22

17/02/2019 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Variables and its Scope

• Variables can be declared using var


• Two scopes:
• a global scope for declaring global variables,
• a function scope for declaring variables that are local to a function.
• A local variable masks a global variable that has the same name.
• JavaScript 6 using Let has two scopes: 1) a global scope for declaring global
variables, and 2) a block scope for declaring variables between { and }.

23

17/02/2019 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Variables
variables are declared with the var keyword (case sensitive)
types are not specified, but JS does have types ("loosely typed")
– Number, Boolean, String, Array, Object, Function, Null,
Undefined
– can find out a variable's type by calling typeof

var name = expression;


JS
var clientName = "Connie Client";
var age = 32;
var weight = 127.4;
JS
CSI ZG526 Web Technologies 24
Number type
integers and real numbers are the same type (no int vs. double)
same operators: + - * / % ++ -- = += -= *= /= %=
similar precedence to Java
many operators auto-convert types: "2" * 3 is 6

var enrollment = 99;


var medianGrade = 2.8;
var credits = 5 + 4 + (2 * 3);

JS

CS380

CSI ZG526 Web Technologies 25


Primitive Data Types

• A primitive is data that is not an object and has no methods. A


primitive value is represented directly at the lowest level of the
language implementation.
• All primitives are immutable, i.e., they cannot be altered. It is important
not to confuse a primitive itself with a variable assigned a primitive value.
The variable may be reassigned a new value, but the existing value can not
be changed in the ways that objects, arrays, and functions can be altered.

26

17/02/2019 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Primitive Data types

• JavaScript has five primitive types:


• Number,
• String,
• Boolean,
• Undefined, and
• Null
Example
let myString = 'Hello';
let myNumber = '500';
typeof myNumber; String
myNumber = 500;
typeof myNumber; Number
let x; undefined
let flag =true; boolean
let y=null; null
27

17/02/2019 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Number

• All numeric values are stored in double-precision floating point


• All arithmetic operations can be performed on Numbers.
• There is no specific type for integers.
• In addition to being able to represent floating-point numbers, the number type
has three symbolic values: +Infinity, -Infinity, and NaN (not-a-number).
• To check for the largest available value or smallest available value within +/-
Infinity, you can use the constants Number.MAX_VALUE or
Number.MIN_VALUE

28

17/02/2019 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Numeric Operators

29

17/02/2019 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Boolean, Null, Undefined

Boolean
A boolean represents only one of two values: true, or false. Think of a boolean as an on/off or a
yes/no switch.
var boo1 = true;
var boo2 = false;
Null
Null has one value: null. It is explicitly nothing.
var nothing = null;
The only Null value is null
Undefined
A variable that has no value is undefined.
var testVar;
console.log(testVar); // undefined
30

17/02/2019 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Special values: null and undefined
undefined : has not been declared, does not
exist
null : exists, but was specifically assigned an
empty or null value var ned = null;
var benson = 9;
// at this point in the code,
// ned is null
// benson's 9
// caroline is undefined

JS

CSI ZG526 Web Technologies 31


NaN

• NaN - Not a Number


• NaN is a JavaScript reserved word indicating that a number is not a legal
number.
• var x = 100 / "Apple"; // x will be NaN (Not a Number)

• var x = 100 / "Apple";


• isNaN(x);
• NaN is a number:

32

17/02/2019 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Comments (same as Java)
identical to Java's comment syntax
recall: 4 comment syntaxes
– HTML: <!-- comment -->
– CSS/JS/PHP: /* comment */
– Java/JS/PHP: // comment
– PHP: # comment

// single-line comment
/* multi-line comment */
JS

CSI ZG526 Web Technologies 33


Logical operators

> < >= <= && || ! == != === !==


most logical operators automatically convert types:
5 < "7" is true
42 == 42.0 is true
"5.0" == 5 is true
=== and !== are strict equality tests; checks both
type and value
"5.0" === 5 is false

CS380

CSI ZG526 Web Technologies 34


if/else statement (same as Java)
if (condition) {
statements;
} else if (condition) {
statements;
} else {
statements;
}

JS
identical structure to Java's if/else statement
JavaScript allows almost anything as a condition

CSI ZG526 Web Technologies 35


Boolean type
var iLike190M = true;
var ieIsGood = "IE6" > 0; // false
if ("web devevelopment is great") { /* true
*/ }
if (0) { /* false */ }

any value can be used as a Boolean


"falsey" values: 0, 0.0, NaN, "", null, and undefined
"truthy" values: anything else
converting a value into a Boolean explicitly:
var boolValue = Boolean(otherValue);
var boolValue = !!(otherValue);
CSI ZG526 Web Technologies 36
for loop (same as Java)
var sum = 0;
for (var i = 0; i < 100; i++) {
sum = sum + i;
}
var s1 = "hello";
JS
var s2 = "";
for (var i = 0; i < s.length; i++) {
s2 += s1.charAt(i) + s1.charAt(i);
}
// s2 stores "hheelllloo"
JS

CS380

CSI ZG526 Web Technologies 37


while loops (same as Java)
while (condition) {
statements;
}
JS
do {
statements;
} while (condition);

JS

break and continue keywords also behave as in


Java
CS380

CSI ZG526 Web Technologies 38


Object Wrappers
var name = 'John';
console.log(name.length); //prints 4
console.log(name.toUpperCase()); //prints JOHN
typeof 'John' //string

Javascript detects that you are trying to access a property of a string primitive.
It creates a wrapper object String to wrap the original string primitive.
It accesses the length and toUpperCase on the wrapper object instead of the original primitive.
It discards the wrapper object, frees the memory and continues.

39

17/02/2019 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Manually creating wrappers

• In the example above, JavaScript creates wrapper objects automatically under the hood. There is also
a way to create such objects explicitly.
• new Number(4)
• new String('Hi')
• new Boolean(true)
• These are not primitives anymore, but objects, which contain the primitive value and add some extra
goodies.
• typeof 4 //number
• typeof 'Hi' //string
• typeof true //boolean

• typeof new Number(4) //object


• typeof new String('Hi') //object
• typeof new Boolean(true) //object
40

17/02/2019 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
BITS Pilani
Hyderabad Campus

Thank You
CSI ZG526 Web Technologies
II Sem 2018-19

BITS Pilani Akshaya Ganesan


BITS-Pilani
BITS Pilani
Hyderabad Campus

Lecture 7: Javascript

2
Array

• An array is a single object that contains multiple values enclosed in square brackets and separated by
commas.
• var myNameArray = ['Chris', 'Bob', 'Jim'];
• var myNumberArray = [10,15,40];
• Once these arrays are defined, you can access each value by their location within the array.
• myNameArray[0]; // should return 'Chris'
• myNumberArray[2]; // should return 40

• Values of an array need not be of the same data type


• var mix = [“hi”, 1, 2, “hello”];
• mix[0] is String, mix[1] is number

17/02/2019 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Arrays
var name = []; // empty array
var name = [value, value, ..., value]; //
pre-filled
name[index] = value; // store element

var ducks = ["Huey", "Dewey", "Louie"];


var stooges = []; // stooges.length is 0
stooges[0] = "Larry"; // stooges.length is 1
stooges[1] = "Moe"; // stooges.length is 2
stooges[4] = "Curly"; // stooges.length is 5
stooges[4] = "Shemp"; // stooges.length is 5
JS

CSI ZG526 Web Technologies 4


Array methods
var a = ["Stef", "Jason"]; array serves as many data structures: list,
// Stef, Jason queue, stack, ...
a.push("Brian");
// Stef, Jason, Brian methods: concat, join, pop, push,
reverse, shift, slice, sort, splice,
a.unshift("Kelly");
toString, unshift
// Kelly, Stef, Jason,
Brian push and pop add / remove from back
a.pop(); unshift and shift add / remove from front
// Kelly, Stef, Jason shift and pop return the element that is removed
a.shift(); // Stef, Jason
a.sort(); // Jason, Stef

5
String type
methods: charAt, charCodeAt, fromCharCode, indexOf,
lastIndexOf, replace, split, substring, toLowerCase,
toUpperCase
– charAt returns a one-letter String (there is no char type)

length property (not a method as in Java)


Strings can be specified with "" or ''
concatenation with + : var s = "Connie Client";
– 1 + 1 is 2, but "1" + 1 is "11" var fName = s.substring(0, s.indexOf(" "));
// "Connie"
var len = s.length; // 13
var s2 = 'Melvin Merchant';

JS
CSI ZG526 Web Technologies 6
More about String
escape sequences behave as in Java: \' \" \& \n \t \\
converting between numbers and Strings:
var count = 10;
var s1 = "" + count; // "10"
var s2 = count + " bananas, ah ah ah!"; // "10
bananas, ah ah ah!"
JS
var firstLetter = s[0]; // fails in IE
var firstLetter = s.charAt(0); // does work
in IE
var lastLetter = s.charAt(s.length - 1);
JS
CS380

CSI ZG526 Web Technologies 7


Splitting strings: split and join
split breaks apart a string into an array using a
delimiter
can also be used with regular expressions (seen later)
join merges an array into a single string, placing a
delimiter between them

var s = "the quick brown fox";


var a = s.split(" "); // ["the", "quick", "brown", "fox"]
a.reverse(); // ["fox", "brown", "quick", "the"]
s = a.join("!"); // "fox!brown!quick!the"
JS

CSI ZG526 Web Technologies 8


Array and String Methods

Numbers vs. strings


'Front ' + 242;
var myDate = '19' + '67‘
The Number object will convert anything
passed to it into a number
var myString = '123'; var myNum =
Number(myString);
every number has a method called toString()
that will convert it to the equivalent string
var myNum = 123; var myString =
myNum.toString();

17/02/2019 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Converting between Strings and Arrays

var myData = 'Manchester,London,Liverpool,Birmingham,Leeds,Carlisle';


var myArray = myData.split(',');

myArray.length;
myArray[0]; // the first item in the array
myArray[1]; // the second item in the array
myArray[myArray.length-1]; // the last item in the array
var myNewString = myArray.join(',');

myNewString; var dogNames = ["Rocket","Flash","Bella","Slugger"];


dogNames.toString(); //Rocket,Flash,Bella,Slugger 10

17/02/2019 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Functions

Function is a block of organised code.


User defined functions and Predefined functions.

function hello() {
console.log(“Hi”);
}
hello();

11

17/02/2019 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Function Expression:

When a function is assigned to a variable. The function can be named, or


anonymous. Use the variable name to call a function defined in a function
expression.
// anonymous function expression
var doSomething = function(y) {
return y + 1;
};
// named function expression
var doSomething = function addOne(y) {
return y + 1;
};
12

17/02/2019 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Functions with a variable number of
parameters
An array named "arguments" is created automatically in each function, it
contains all the call parameters of the function:
function f() {
return arguments;
}
f(); // returns []
f( 1, 2, 3, 4, true, 'Michel Buffa'); // returns [1, 2, 3, 4, true, "Michel Buffa"]
function sum(a, b) {
var c = a + b;
return c;
}
sum(1)
13
NaN is assigned to one of the parameters
17/02/2019 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Objects

• A primitive value is a value that has no properties or methods.


• var person = "John Doe";
• Objects are variables too. But objects can contain many values.
• The values are written as name : value pairs (name and value separated by a colon)
var person = {firstName:"John",
lastName:"Doe",
age:50,
eyeColor:"blue"};

Accessing property:
objectName.property // person.age
or
objectName["property"] // person["age"]
14

17/02/2019 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Creating Objects

• Define and create a single object, using an object literal.


• Define and create a single object, with the keyword new.
• Define an object constructor, and then create objects of the constructed type.

• Using an object literal, you both define and create an object in one statement.
• An object literal is a list of name:value pairs (like age:50) inside curly braces {}.
• var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
• var person = {
• firstName:"John",
• lastName:"Doe",
• age:50,
• eyeColor:"blue"
• };

15

17/02/2019 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Using the JavaScript Keyword new

var person = new Object();


person.firstName = "John";
person.lastName = "Doe"; The syntax for accessing the property of an
object is:
person.age = 50;
objectName.property // person.age
person.eyeColor = "blue"; or
objectName["property"] // person["age"]
Objects are Mutable or
var x = person; objectName[expression]
// x = "age";person[x]
X points to person
16

17/02/2019 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Creating Objects Using Constructors

• we need a "blueprint" for creating many objects of the same "type".

• The way to create an "object type", is to use an object constructor function.

• In the example above, function Person() is an object constructor function.

• Objects of the same type are created by calling the constructor function with
the new keyword:

• var myFather = new Person("John", "Doe", 50, "blue");


• var myMother = new Person("Sally", "Rally", 48, "green");
17

17/02/2019 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
This Keyword

In JavaScript, the thing called this, is the object that "owns" the JavaScript code.
The value of this, when used in a function, is the object that "owns" the function.

You access an object method with the following syntax:


objectName.methodName()
name = person.fullName();

function Person(first, last, age, eye) {


this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}

18

17/02/2019 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
References and objects

Unlike a pointer variable, which contains the actual address of an object within
the memory, a reference variable is an alias to a variable. This means that
when you modify a reference variable, the original variable is modified too.
This is because the two variables reference (i.e. point to) the same object.
If its value is a primitive value (number, string, or boolean), the variable contains
this value directly.
If its value is an object, the variable contains the memory address of the object.
JavaScript is a "pass by value" language, unlike some other languages, which
are "pass by reference" languages. This means that when you pass a
variable to a function as argument, the value of the variable is copied into the
argument.

19

17/02/2019 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Example 1
var x = 2; // the variable x contains the primitive data 2
var y = { a: 2 } // The variable y references the object {a: 2}

// "Copying" two variables


var x2 = x;
var y2 = y;
Var y3 = y ;

// Modifying copied variables


x2 = 3;
y2 = { a: 3 };

x; // 2 <- x is not modified because it contains a primitive value


y; // { a: 2 } <- y is not modified because y2 does not point to same object
y3.a = 4;
y; // { a: 4 } <- The object referenced by "y" and "y3" is modified
20

17/02/2019 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Example 2

var x = 2;
function sum(a, b) {
a = a + b;
return a;
}
sum(x, 3); // returns 5
x; // 2 <- but x equals 2

var obj = { x: 2 }
function add(a, b) {
a.x += b;
}
add(obj, 3);
obj.x; // 5 <- The referenced object is modified
21

17/02/2019 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Objects in JavaScript

In JavaScript, almost "everything" is an object.


Booleans can be objects (if defined with the new keyword)
Numbers can be objects (if defined with the new keyword)
Strings can be objects (if defined with the new keyword)
Dates are always objects
Maths are always objects
Regular expressions are always objects
Arrays are always objects
Functions are always objects

22

17/02/2019 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
More on Arrays

Arrays are Objects


Arrays are a special kind of objects, with numbered indexes.
The typeof operator in JavaScript returns "object" for arrays.
The length property of an array returns the length of an array
Built in methods are available to sort, iterate through arrays
Add a new element to an array is using the push method:

var fruits = ["Banana", "Orange", "Apple", "Mango"];


fruits.push("Lemon");
The pop() method removes the last element from an array:
The splice() method can be used to add new items to an array:

var fruits = ["Banana", "Orange", "Apple", "Mango"];


fruits.splice(2, 0, "Lemon", "Kiwi");
23

17/02/2019 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
More on Strings

Normally, JavaScript strings are primitive values, created from literals:


var firstName = "John"; type String
But strings can also be defined as objects with the keyword new:
var firstName = new String("John"); type object

var x = "John";
var y = new String("John");
// (x == y) is true because x and y have equal values
// (x === y) is false because x and y have different types (string and object)

String methods
Slice(), concat(), reverse(), indexOf(), substr()

24

17/02/2019 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Comparing two objects
Comparing two objects will only return true if they point to the same object
Two objects of the same type, with the same property value, that look identical, will not be equal one to another
> var originalObject = {name:'Michel'};

> var copy = originalObject;

> copy === originalObject


true

> var anotherObject = {name:'Michel'};

> copy === anotherObject


false

25

17/02/2019 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
valueOf and toString

There are some cases when you would rather need a primitive representation
of the object. Actually, javascript offers two methods for it which each object
inherits:
valueOf() returns primitive representation of the object
toString() returns string representation of the object
A good example can be Date. toString() returns a human-readable description of the date, while valueOf()
returns a number representing the date as the number of passed milliseconds since 1 January 1970
00:00:00 UTC and the date.
var date = new Date();
console.log(date.toString()); //Wed Jan 24 2018 14:12:07 GMT+0100 (Central Europe Standard Time)
console.log(date.valueOf()); //1516817671281

26

17/02/2019 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Popup boxes
alert("message"); // message
confirm("message"); // returns true or
false
prompt("message"); // returns user input
string
JS

CSI ZG526 Web Technologies 27


Dialog Boxes

JavaScript supports three important types of dialog boxes.


These dialog boxes can be used to raise an alert, or to get confirmation on any
input or to have a kind of input from the users.

Alert Box
alert(“The sum is:” + sum + ”\n");
Parameter is plain text, not HTML
Opens a dialog box which displays the parameter string and an OK button
It waits for the user to press the OK button

28

23-02-2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Dialog Boxes

Confirm
var question = confirm("Do you want to continue this
download?");
Opens a dialog box and displays the parameter and two buttons, OK and Cancel
Returns a Boolean value, depending on which button was pressed (it waits for one)

29

23-02-2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Dialog Boxes

Prompt
prompt("What is your name?", “ ");
– Opens a dialog box and displays its string parameter, along with a text box and two buttons,
OK and Cancel
– The second parameter is for a default response if the user presses OK without typing a
response in the text box (waits for OK)

30

23-02-2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Date Object

• The Date object is a datatype built into the JavaScript language


• Creating Date Objects
• A date consists of a year, a month, a day, an hour, a minute, a second, and
milliseconds.
• Date objects are created with the new Date() constructor.
There are 4 ways of initiating a date:
new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)

31

23-02-2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Math Object

• The math object provides you properties and methods for mathematical
constants and functions.

• The Math Object provides floor, round, max, min, trig functions, etc.
• e.g., Math.cos(x)

32

23-02-2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Regular Expression Object
• A regular expression is an object that describes a pattern of characters.
• RegExp define methods that use regular expressions to perform powerful pattern-matching and search-and-replace
functions on text
• var pattern = new RegExp(pattern, attributes);

• Using test()
• The test() method is a RegExp expression method.
• It searches a string for a pattern, and returns true or false, depending on the result.
• var patt = /e/;
• patt.test("The best things in life are free!");
• Using exec()
• The exec() method is a RegExp expression method.
• It searches a string for a specified pattern, and returns the found text.
• If no match is found, it returns null.
• /e/.exec("The best things in life are free!");

33

23-02-2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Regular Expression

Expression Description

[abc] Find any character between the brackets

[^abc] Find any character NOT between the brackets

[0-9] Find any character between the brackets (any digit)

[^0-9] Find any character NOT between the brackets (any non-digit)

(x|y) Find any of the alternatives specified

34

23-02-2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Error Handling in JS

• When executing JavaScript code, different errors can occur.


• Errors can be coding errors made by the programmer, errors due to wrong input, and other
unforeseeable things.
• JavaScript try and catch
• The try statement allows you to define a block of code to be tested for errors while it is being executed.
• The catch statement allows you to define a block of code to be executed, if an error occurs in the try
block.
• try {
• Block of code to try
• }
• catch(err) {
• Block of code to handle errors
• }

35

23-02-2019 CSIZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
DOM

• The Document Object Model (DOM) is a interface between HTML and Javascript
• It represents the webpage, programs can change the document structure, style, and content.
• The DOM represents the document as nodes and objects.
• A Web page is a document. This document can be either displayed in the browser window or
as the HTML source.
• The Document Object Model (DOM) represents that same document so it can be
manipulated.
• The DOM is an object-oriented representation of the web page, which can be modified with a
scripting language such as JavaScript.
• Different browsers have different implementations of the DOM, but every web browser uses
some document object model to make web pages accessible via JavaScript.

36

08/09/2018 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
DOM

• The DOM is a W3C (World Wide Web Consortium) standard.


• The DOM defines a standard for accessing documents:

• "The W3C Document Object Model (DOM) is a platform and language-neutral interface that
allows programs and scripts to dynamically access and update the content, structure, and
style of a document."

• The W3C DOM standard is separated into 3 different parts:

• Core DOM - standard model for all document types


• XML DOM - standard model for XML documents
• HTML DOM - standard model for HTML documents

37

08/09/2018 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
HTML DOM

• The HTML DOM is a standard object model and programming interface for HTML. It defines:

• The HTML elements as objects


• The properties of all HTML elements
• The methods to access all HTML elements
• The events for all HTML elements
• In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML elements.
• Every element in a document—the document as a whole, the head, tables within the document, table
headers, text within the table cells—is part of the document object model for that document, so they
can all be accessed and manipulated using the DOM and a scripting language like JavaScript.

38

08/09/2018 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
DOM

<html>
<head>
<title>My title</title>
</head>
<body>
<a href=“link”>My Link</a>
<h1>My header</h1>
</body>
</html>

39

08/09/2018 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Document Object

The document object represents your web page.


To access any element in an HTML page, start with accessing the document
object.
Use the document object to access and manipulate HTML.

• Document.URL
• Document.body
• Document.links
• Document.head

40

08/09/2018 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Use the document object to access

• document.getElementById(id) Find an element by element id


• document.getElementsByTagName(name) Find elements by tag name
• document.getElementsByClassName(name) Find elements by class name
• document.querySelector(CSS Selectors)
– returns the first element that matches a specified CSS selector(s)

• document.querySelectorAll()

41

08/09/2018 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
DOM Nodes

• According to the W3C HTML DOM standard, everything in an HTML document is a node:

• The entire document is a document node


• Every HTML element is an element node
• The text inside HTML elements are text nodes
• Every HTML attribute is an attribute node
• All comments are comment nodes
• DOM HTML tree
• With the HTML DOM, all nodes in the node tree can be accessed by JavaScript.

• New nodes can be created, and all nodes can be modified or deleted.

42

08/09/2018 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
DOM TREE

Picture Reference:W3Schools 43

08/09/2018 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Element Access in JavaScript

There are several ways to do it


1. DOM address
– Example (a document with just one form and one widget):
<form action = "">
<input type = "button" name = "pushMe">
</form>
– document.forms[0].elements[0]
– Problem: document changes

44

08/09/2018 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Element Access in JavaScript

2. Element names
– requires the element and all of its ancestors (except body) to have name
attributes
– Example:
<form name = "myForm" action = "">
<input type = "button" name = "pushMe">
</form>
– document.myForm.pushMe

45

08/09/2018 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Element Access in JavaScript

3. getElementById Method (defined in DOM 1)


– Example:
<form action = "">
<input type = "button" id = "pushMe">
</form>
– document.getElementById("pushMe")
Form elements often have ids and names both set to the same value

46

08/09/2018 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Element Access in JavaScript

Checkboxes and radio button have an implicit array, which has their name
<form id = "toppingGroup">
<input type = "checkbox" name = "toppings"
value = "olives" />
... <input type = "checkbox" name = "toppings"
value = "tomatoes" />
</form>
...
var numChecked = 0;
var dom = document.getElementById("toppingGroup");
for (index = 0; index < dom.toppings.length; index++)
if (dom.toppings[index].checked]
numChecked++;

47

08/09/2018 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
The HTMLCollection Object

• The getElementsByTagName() method returns an HTMLCollection object.

• An HTMLCollection object is an array-like list (collection) of HTML elements.

• The following code selects all <p> elements in a document:

• Example
• var x = document.getElementsByTagName("p");
• The elements in the collection can be accessed by an index number.

• To access the second <p> element you can write:


• y = x[1];

48

08/09/2018 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
NodeList

• The HTML DOM NodeList Object


• A NodeList object is a list (collection) of nodes extracted from a document.

• A NodeList object is almost the same as an HTMLCollection object.

• Some (older) browsers return a NodeList object instead of an HTMLCollection for methods like
getElementsByClassName().

• All browsers return a NodeList object for the property childNodes.


• Most browsers return a NodeList object for the method querySelectorAll().
• HTMLCollection items can be accessed by their name, id, or index number.

• NodeList items can only be accessed by their index number.

49

08/09/2018 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
DOM Manipulation

• changing an element's style


• adding/removing classes
• changing the content of a tag
• changing attributes(src, href, etc.)

50

08/09/2018 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Changing Style and class

• element.style.property = new style Change the style of an HTML element


• But separtion of concern is a problem.
• Styles are place in CSS files

Solution:
• we can define a CSS class and then toggle it on or off with JS. Using classlist
• var tag = document.getElementById("highlight");
• tag.classList.add("some-class");
• The classList property returns the class name(s) of an element.
• This property is useful to add, remove and toggle CSS classes on an element.
• The classList property is read-only, however, you can modify it by using the add() and
remove() methods.

51

08/09/2018 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
changing the content of a tag

• /Select the <p> tag:


• var tag = document.querySelector("p");

• //Retrieve the textContent:


• tag.textContent =new content

• Similar to textContent, except it returns a string of all the HTML contained in a given element
• var tag = document.querySelector("p");
• tag.innerHTML –new content

52

08/09/2018 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Changing attributes

• Use getAttribute() and setAttribute() to read and write attributes like src or
href
• element.attribute = new value Change the attribute value of an HTML
element
• element.setAttribute(attribute, value) Change the attribute value of an HTML
element

53

08/09/2018 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Navigating Between Nodes

<html>

<head> parentNode
<title>DOM Tutorial</title> childNodes[node
</head> number]
firstChild
<body> lastChild
<h1>DOM Lesson one</h1> nextSibling
<p>Hello world!</p> previousSibling
</body>

</html>
54

08/09/2018 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
NODES

DOM Root Nodes


– document.body - The body of the document
– document.documentElement - The full document

The nodeName Property


– nodeName is read-only
– nodeName of an element node is the same as the tag name
– nodeName of an attribute node is the attribute name
– nodeName of a text node is always #text
– nodeName of the document node is always #document

The nodeValue Property


– nodeValue for element nodes is undefined
– nodeValue for text nodes is the text itself
– nodeValue for attribute nodes is the attribute value

55

08/09/2018 CSI ZG526 Web Technologies BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
BITS Pilani
Hyderabad Campus

Thank You
Birla Institute of Technology and Science, Pilani
Work Integrated Learning Programme
LAB HANDOUT

Course Web Technologies


Module Lab Handout-Module 1
Objective  To understand the working of HTTP
 To Understand the HTTP Request and Response Headers
 To understand the various HTTP methods
Contents  Using Developer tools of Chrome Browser
 Using Curl to initiate HTTP request and Receive response
 Use Wireshark to analyse the HTTP and HTTPS packets
References  https://developer.mozilla.org/en-US/docs/Web/HTTP
 https://developers.google.com/web/tools/chrome-
devtools/network-performance/reference

PART –A

Exercise 1
Objective:
To understand how HTTP request and Responses are sent between the client to
browser.
Explanation:
Recorded Demo 1: Demonstration of HTTP requests generated and response
received for a Website

Practice Exercises:

1) With the developer tools open in any browser, Monitor/trace the


requests/responses for the websites listed below in the developer Tools and
understand the behavior
 www.news18.com
 www.amazon.in
 www.google.com
 www.shopclues.com
 www.makemytrip.com
i) For each of the websites note down the total number of requests,
amount of data transferred.
ii) Analyse the number of CSS files, javascript files, images fetched for
each of these web sites.
iii) Fill a form in the any of the websites and monitor how the user data is
appended in a POST request

EXERCISE 2:

Objective:
To use the curl command to generate http request using various HTTP
Methods

Explanation:
cURL is a computer software project providing a library and command-line tool
for transferring data using various protocols.

The URL could itself refer to a web page, an image or a file. The client issues a
GET request to the server and receives the document it asked for. If you issue
the command line

curl https://www.google.com

you get a web page returned in your terminal window. The entire HTML
document that that URL holds.

All HTTP replies contain a set of response headers that are normally hidden, use
curl's --include (-i) option to display them as well as the rest of the document.

HEAD
You can ask the remote server for ONLY the headers by using the --head (-I)
option which will make curl issue a HEAD request.

The HEAD method is defined and made so that the server returns the headers
exactly the way it would do for a GET, but without a body. It means that you
may see a Content-Length: in the response headers, but there must not be an
actual body in the HEAD response.

3.3 Multiple URLs in a single command line


A single curl command line may involve one or many URLs. The most common
case is probably to just use one, but you can specify any amount of URLs. Yes
any. No limits. You'll then get requests repeated over and over for all the given
URLs.

Example, send two GETs:


curl http://url1.example.com http://url2.example.com

If you use --data to POST to the URL, using multiple URLs means that you
send that same POST to all the given URLs.

Example, send two POSTs:

curl --data name=curl http://url1.example.com http://url2.example.com

Multiple HTTP methods in a single command line


Sometimes you need to operate on several URLs in a single command line and
do different HTTP methods on each. For this, use the --next option. It is
basically a separator that separates a bunch of options from the next. All the
URLs before --next will get the same method and will get all the POST data
merged into one.

When curl reaches the --next on the command line, it'll sort of reset the method
and the POST data and allow a new set.

Perhaps this is best shown with a few examples. To send first a HEAD and then
a GET:

curl -I http://example.com --next http://example.com

To first send a POST and then a GET:

curl -d score=10 http://example.com/post.cgi --next


http://example.com/results.html

Practice Exercise:

1) Initiate the Get request to www.google.com using curl. Observe the


Response.
2) Send a POST request to any website using curl
3) Initiate a HEAD request to bits-pilani.ac.in and www.bits-pilani.ac.in.
Identify the difference in the response headers and write them
Exercise 3

Objective:
To analyse the HTTP and HTTPs packets using Wireshark.

Explanation:
Wireshark is a free and open-source packet analyzer. It is used for
network troubleshooting, analysis, software and communications protocol
development, and education.

Use the following link for downloading Sample captures


https://wiki.wireshark.org/SampleCaptures#HyperText_Transport_Protoc
ol_.28HTTP.29

Or You can also capture new HTTP and HTTPS traffic

To use:

1. Install Wireshark.
2. Open your Internet browser.
3. Clear your browser cache.
4. Open Wireshark
5. Click on "Capture > Interfaces,
6. You probably want to capture traffic that goes through your
ethernet driver. Click on the Start button to start capturing traffic via this
interface.
7. Visit the URL that you wanted to capture the traffic from.
8. Go back to your Wireshark screen and press Ctrl + E to stop
capturing.
9. After the traffic capture is stopped, please save the captured traffic
into a *.pcap format file and attach it to your support ticket.

Practice Exercise:

1) Analyze the HTTP request headers and information in the captured


traffic
2) Analyze the TLS handshake in the HTTPS capture.
3) Monitor the client Hello, Server Hello Messages.
4) List down the cipher suite selected by the Server for encryption and
decryption
Birla Institute of Technology and Science, Pilani
Work Integrated Learning Programme
LAB HANDOUT

Course Web Technologies


Module Lab Handout-Module 2
Objective  To understand the various basic structure of HTML web page
 To create web pages using HTML
Contents To create web pages using HTML

References https://developer.mozilla.org/en-US/docs/Web

PART –A

Exercise 1
Objective:
To understand the basic structure of HTML and the basic tags
Explanation:
Recorded Demonstration 2: To understand the basic tags

Practice Exercises:

1) Write a HTML code using <table> tag to create a table structure as shown below. Use
spanning of columns and rows wherever necessary. [

2) Create a HTML page which embeds a youtube video in it. Place the video exactly in
the center of the web page. Add a Header and footer section to the web page with
appropriate information
3) Create a HTML form as shown below. Add input elements like color chooser, date
picker, meter, range etc., to make the form user friendly. Also group the iput types
into fieldset and label them using legend

4) Create an Online Resume webpage for yourself in the format given below. Start with
your name, address and phone number. Use an alternate typeface such as Arial.
Birla Institute of Technology and Science, Pilani
Work Integrated Learning Programme
LAB HANDOUT

Course Web Technologies


Module Lab Handout-Module 3
Objective  To understand the CSS
 Apply styling effects to HTML web Pages

Contents  Using Developer tools of Chrome Browser


 Using CSS3 to format web pages

References  https://developer.mozilla.org/en-US/docs/Web/

PART –A

Objective:
To understand the use and need of CSS
Explanation:
Recorded Demo : Use of CSS to add effects to web pages
Select elements using CSS Selectors

Practice Exercises:

1) Below is the HTML code of a BITS Pilani course web page without CSS.
The webpage contains various sections header, menu, link, footer etc.,
Use css and add a external stylesheet reference to the web page.
Code for Web Page:
<!DOCTYPE html>
<html>
<head>
<title>BITS Pilani Course Directory</title>
</head>
<body>
<div id="container">
<header>
<h1><span class="blue-text"> BITS Pilani</span> Course
Directory</h1>
<h2>Find a course <span class="white-
text">NOW</span></h2>
</header>
<nav id="menu">
<ul>
<li class="menu"><a href="index.html">Home</a></li>
<li class="menu"><a href="about.html">About
Us</a></li>
<li class="menu"><a
href="browse.html">Courses</a></li>
<li class="menu"><a href="contact.html">Contact
Us</a></li>
</ul>
</nav>

<aside>
<nav id="leftmenu">
<h3>Links</h3>
<ul>
<li><a href="browse.html">DBMS</a></li>
<li><a href="browse.html">PHP</a></li>
<li><a href="browse.html">DevOps</a></li>
<li><a href="browse.html">jQuery</a></li>
<li><a href="browse.html">Web design</a></li>
<li><a href="browse.html">Web
Programming</a></li>
<li><a
href="browse.html">Microservices</a></li>
<li><a href="browse.html">Internet
Marketing</a></li>
<li><a href="browse.html">XHTML
Templates</a></li>
</ul>
</nav>
</aside>

<section>
<h2>BITS Pilani Course Directory </h2>
<h3>Who Are We?</h3>
<p> Search and browse courses </p>
<h3>What are the courses we have?</h3>
<p>Our course languages like HTML5, XHTML and XML to programming languages
such as Javascript, PHP, Python and ASP</p>
</section>
</div><!--container end-->
<div style="clear;both"></div>
<footer>
Copyright &copy; 2018, BITS-Pilani
</footer>
</body>
</html>

2) Write an HTML document that shows the results of a color survey. The document
should contain a form with radio buttons that allows users to votefor their favorite
color. One of the colors should be selected as a default. The document should also
contain a table showing various colors and the corresponding percentage of votes for
each color. (Each row should be displayed in the color to which it is referring.) Use
attributes to format width, border and cell spacing for the table
3) Box Model Exercise
Copy this webpage code.
Add appropriate margin, border, and padding to the text div.
Add appropriate border to the image.
Create a div for all of the page content and center that in the middle of the
page. Add appropriate border and padding to that div.
Experiment with different values for box model properties and
understand the positioning of element

CODE:
<!DOCTYPE html>
<html>
<head>
<style>
div.ex1 {
width: 300px;
background-color: yellow;
}
div.ex2 {
width: 300px;
padding: 5px;
box-sizing: border-box;
background-color: lightblue;
}
</style>
</head>
<body>
<h2>Padding and element width</h2>
<img src="Logo.png" width="100" height="100">BITS-Logo</img>
<div class="ex1">This div is 300px wide.</div>
<br>
<div class="ex2">The width of this div remains at 300px, in spite of
the 50px of total left and right padding, because of the box -sizing:
border-box property.

</body>
</html>

4) To get an idea of the practicalities of positioning use the example


demonstrated in the following link. Download the code and try with
different values

https://developer.mozilla.org/en-
US/docs/Learn/CSS/CSS_layout/Practical_positioning_examples

5) For each of the following CSS rule(s), write the words (e.g. “Div2”) that will appear
red or green in the browser and specify the color. Rules from one part do not apply to
the next part. Briefly justify your answers for each part by stating what the CSS rules
are doing.
Code:
<html>
<body>
<div id="div1">Div1</div>
<div id="div2" class="class1">Div2</div>
<div>Div3
<span id="span1" class="class1">span1</span>
<span id="span2" class="class2">span2</span>
</div>
<div>Div4</div>
<span>span3</span>
</body>
</html>

CSS RULES:

(a) div { color: red}


(b) div.class1 { color: red}
(c) .class1 { color: red}
(d) #span2 {color: red}
(e) div { color: red} div.class1 {color: green}
Birla Institute of Technology and Science, Pilani
Work Integrated Learning Programme
LAB HANDOUT

Course Web Technologies


Module Lab Handout-Module 4
Objective  To understand the basics of Javascript
Contents  Simple Exercises using Javascript
References  https://developer.mozilla.org/en-US
 Robert W. Sebesta, Programming the World Wide Web, 7th Ed,
Pearson
 Harvey M. Deitel and Paul J. Deitel, Internet & World Wide Web
How to Program, 4th edition

PART –A

Exercise 1:

1) Predict the output


var globalVar = 1;
function foo(argVar) {
var localVar = 2;
return function (arg) {
argVar += arg;
localVar += arg;
globalVar += arg;
console.log('F', argVar, localVar, globalVar);
};
}
var func1 = foo(1);
var func10 = foo(10);
func1(1);
func10(2);
console.log('G', globalVar);

2) What will be the output of the code below?


<script>
var x = '5';
console.log(x===5);
console.log(x==5);
console.log(x==='5');
console.log(x=='5');
</script>
3) Write a JavaScript function to change the background color of a paragraph element
<p> to “red” when the button is clicked.

<html>
<body>
<input type="button" value="Click to set paragraph background color"
onclick="set_background()">
<p>This is a paragraph element </p>
</body>
</html>

4) Write a function greet having one parameter and returning "Hello


<parameter>!". greet("Ajay") should return "Hello Ajay!" and greet("Tan")should
return "Hello Tan!".

5) Write a function normalize, that replaces "-" with "/" in a date string.normalize("20-
05-2017") should return "20/05/2017".
HINT:
The replace method replaces a substring with another:
var str = "JavaScript";
var newstr = str.replace("Java", "ECMA");
"Java" is replaced with "ECMA". Thus newstr has the value "ECMAScript". The
original string remains unchanged. Only the first occurrence is replaced:
var newstr = "Dada".replace("a", "i");
newstr has the value "Dida" and not "Didi".

6) Execute the code below and observe

Code:
<html>
<head>
<script language="JavaScript" type="text/javascript">
function switchTest(SetOption) {
OptionsSelect = document.frmOne.SetOption.value
alert(OptionsSelect);
switch (OptionsSelect) {
case "1":
alert("Arizona")
break
case "2":
alert("New Mexico")
break
case "3":
alert("California")
break
default:
alert("Cannot be determined")
}
}
</script>
<body>
<h3>JavaScript</h3>
<form name = "frmOne">
<select name= "SetOption" onchange="switchTest(this)">
<option value = "0">Select a City - See the State!</option>
<option value = "1">Phoenix</option>
<option value = "2">Roswell</option>
<option value = "3">Sacramento</option>
<option value = "4">My city</option>
<option value = "5">Your city</option>
</select>
</form>
</body>
</html>

You might also like