You are on page 1of 169

Chapter 1: Introduction HTML5

Basic Concepts
What is HTML?
HTML History
Setting up Your Development Environment
Understanding Three Layers of Web: HTML, CSS, JavaScript
Understanding HTML Tags

Chapter 2: Understanding Page Structure


Specifying Document Type
The Head Section
The Body Section
“Hello World” Example
View HTML5 Page in Browser
HTML5 Boilerplate
HTML5 Validation
Adding External Files
Adding Stylesheet to HTML
Adding JavaScript Files to HTML
Organizing File and Folder Structure

Chapter 3: Creating Text Elements


Line Break
Creating Headings
Applying Bold and Italic Formatting
Superscript and Subscript
Block Quotation
Preformatted Text
Unordered, Ordered and Definition Lists
Ordered Lists
Unordered Lists
Nesting Lists
Definition Lists
Using Links & Creating Navigation
Using Relative and Absolute Paths
Setting Link Target:
Linking to a Phone Number
Linking to an E-Mail Address
Creating and Hyperlinking to Anchors
Adding Images
Displaying Data with Tables
Table Row
Table Data
Colspan
Rowspan
Table Heading
Adding Line Break & Horizontal Line
Commenting Your Work

Chapter 4: HTML: Working with Web Forms


Adding Input Boxes
Using Textarea
Using Label
Working with Radio Buttons
Offering Checkbox Options
Implementing Select List
Adding Buttons
Form Processing

Chapter 5: Organizing Page Structure


The Value of Structure: Semantic Elements
The Header Container: <header> Tag
The Footer Content Container: <footer> Tag
The Navigation Container: <nav> Tag
The Main Content Container: <main> Tag
The Page Division Container: <section> Tag
The Independent Content Container: <article> Tag
The Related Content Container: <aside> Tag
Few More Semantic Elements
Adding Contact Information with <address> Tag
The Image Container: <figure> Tag
The Graphics Container: <canvas> Tag
Embedding Audio and Video with <audio>, <video> Tags
The Vector Based Image Container: <svg> Tag

Chapter 6: CSS: Cascading Style Sheets


History of CSS
3 Methods of Adding CSS to HTML File
CSS Rule Structure: CSS Syntax
Using Different Units of Measurement
Block Level vs Inline Elements
Adding CSS Comments
Code Formatting
Validating CSS Code
Chapter 7: CSS: Selectors
Element Selector
ID Selector
Class Selector
Universal Selector
Descendant Selector
Child Selector
Sibling Selector
Attribute Selector
Grouping Elements
Pseudo Class
Inheritance
Specificity Calculator
!important
Chapter 8
Formatting Text
Font Family
Using Web Safe Fonts
Using External Fonts
Using Google Fonts
CSS properties for text management
Adding Colors to Text
Changing Font Size
Font Weight
Font Style
Text Transformation
Text Decoration
Text Alignment
Font Variant
Letter Spacing
Word Spacing
Line Height
Text Indent
Word Wrapping
Styling List Elements
List Style Type
List Style Position
List Style Image
List Style

Chapter 9: Understanding Box Model


Width and Height
Margins and Padding
Adding Borders
Creating Rounded Corners
Background
Background Color
Background Image
Background Repeat
Background Position
Background Size
Background Shorthand Property

Chapter 10: Page Layout


Top, Right, Bottom, Left
Applying Floats to Your Design
Clearing Float
Display Property
Controlling Visibility
Z-index
Controlling Overflow
Working with Flexbox

Chapter 11: Responsive CSS


Different Screens and Screen Sizes
Media Queries

Chapter 12: Advanced CSS and Animation (not for exam/MCA)


Advanced CSS
Text Shadow
Box Shadow
Gradient
Transformations
Transitions

Chapter 13: Introduction to Bootstrap 4


Getting Started with Bootstrap
Bootstrap Grid System
Bootstrap Content Classes
Bootstrap Components and Utilities

Chapter 14: Introduction to JavaScript


Java and JavaScript: The Misunderstanding
Client Server Architecture
Adding JavaScript to HTML Page
“Hello World!” : First JavaScript Project
JavaScript Syntax
Comments
Reserved Words in JavaScript

Chapter 15: Working with Variables and Data Types


Data Types in JavaScript
Working with Numbers
Working with Strings
Understanding Booleans Values
Difference between Undefined and Null
Arrays
Object
Chapter 16: Conditions and Loops
If Statements
Comparison Operators
If-else Statements
If-else-if Statements
Switch Case
Loops: Minimizing Repetition
While Loops
Do-While Loops
For Loops

Chapter 17: Functions: Writing Code for Later


Arguments: Passing Data to Functions
Return Statement: Outputting data from function
Function Scope

Chapter 18: DOM: Document Object Model


Finding Elements by Tag Name
Finding Elements by Class Name
Finding Elements by Id
Finding Parent
Finding Children
Finding Siblings
Interacting with Attributes
Changing Styles

Chapter 19: JavaScript Events


Handling Window Events
Working with Mouse Events
Form Events Handling
Dealing with Key Events

Chapter 20: JavaScript Events


Using jQuery
The $() factory function
Selecting and Manipulating Elements
Get and Set DOM Element Content
Styling Elements
Handling Events

Chapter 21: Latest Trends in JavaScript(Not for exam)


Strict Mode
Regular Expression
Object Oriented JavaScript
Working with AJAX
ECMA Script
Server Side JavaScript: NODE.js
JSON
JavaScript Frameworks: Vue.js, Angular.js, React.js

Chapter 22: Web Design Latest Trends(Not for exam)


Git and Github: Version Control
Gulp: Automated Task Runner
Understanding SASS
Chapter 1

Introduction HTML5

1.0 Objectives
1.1 Introduction
1.2 Basic Concepts
1.2.2 What is HTML?
1.2.3 HTML History
1.2.4 Setting up Your Development Environment
1.3 Understanding Three Layers of Web: HTML, CSS, JavaScript
1.4 Understanding HTML Tags
1.5 Summary
1.6 Check Your Progress Answers

1.0 Objectives
After studying this chapter you will be able to understand
- Basic concepts of Web
- What is HTML and its history
- Three layers of web
- HTML Tags

1.1 Introduction
This chapter gives you clear idea about basic concepts of web like WWW, URL, Web Server, Browsers,
HTML etc. It also teaches you three layers of web page and introduces you to the HTML tags.

1.2 Basic Concepts

World Wide Web


The World Wide Web (WWW) is a network of online content that is organised in HTML and accessed via
HTTP. The word refers to all the interlinked HTML pages that can be reached over the Internet. The World
Wide Web was actually designed in 1991 by Tim Berners-Lee while he was a contractor at CERN. The World
Wide Web is usually referred to as "the Web."

WWW vs Internet
The World Wide Web is what a lot of people think of as the Internet. It is all the Web pages, pictures, videos
and other online content that can be viewed via a Web browser. The Internet, in contrast, is the underlying
network connection that allows us to send email and access the World Wide Web.

URL
URL stands for Uniform Resource Locator, and is used to specify addresses on the World Wide Web. A URL
is the fundamental network identification for any resource connected to the web.

URLs have the following format:


protocol://hostname/other_information

For example, the URL for Indiana University's home page is:

http://www.tmv.edu.in/contactus.asp

Web Server
A web server is a system that provides content or services to end users over the internet. Simply put it is a
computer that hosts a website on the Internet.

Website
A website is a group of publicly available, interlinked Web pages that share a single domain name. Websites
can be developed and maintained by an individual, group, business or organization to provide a variety of
purposes. Often it is called a web site or simply a site.

Web Page
A web page or webpage is a file usually written in HyperText Markup Language (HTML) that is accessible
through the Internet or other network using an Internet browser. A web page is viewed by entering a URL
address and may have text, graphics, and hyperlinks to other web pages and files.

Search Engine
Search Engine is a website that helps you find other web pages. Some of the popular examples of search
engines are Google, Bing and Yahoo.

Browsers
A browser or web browser is a software program built to access content on the World Wide Web. There have
been a number of web browsers that have come and gone over the years. The first, known as
WorldWideWeb (later changed to Nexus), was invented by Tim Berners-Lee in 1990. Some of the current
popular browsers are Google Chrome, Firefox, Opera, Microsoft Internet Explorer or Edge, or Apple's
Safari.

Operating Systems
An operating system (OS) is system software that manages computer hardware and software resources and
provides common services for computer programs. After being initially loaded into the computer by a boot
program, OS manages all the other programs in a computer. The most popular desktop operating system is
the Microsoft Windows. The macOS by Apple Inc. is in second place, and the varieties of the Linux are
collectively in third place. Google's Android and Apple's iOS are dominant operating systems in mobile
sector. While in the web server sector Linux has the major market share.

The operating system manages a computer's hardware resources, including:


• Input devices such as a keyboard and mouse
• Output devices such as display monitors, printers and scanners
• Network devices such as modems, routers and network connections
• Storage devices such as internal and external drives
The OS also provides services to facilitate the efficient execution and management of, and memory
allocations for, any additional installed software application programs.

1.2.1 What Is HTML?


HTML is an acronym for HyperText Markup Language. Basically, a Web page (or HTML document) is a
plain text file that has been encoded using Hypertext Markup Language (HTML) so that it shows up nicely
formatted in a Web browser. Here’s what HTML means, word-by-word:

• Hypertext: Text that you click to jump from document to document. This is a reference to the ability of
Web pages to link to one another.
• Markup: Tags that apply layout and formatting conventions to plain text. Literally, the plain text is
“marked up” with the tags.
• Language: A reference to the fact that HTML is considered a programming language.

How Browsers Style Web Pages


Just like most computer software, a web browser only works with a specified type of file. An HTML page
primarily ends in the file extension of .html. When a browser loads an .html document, it begins to redraw the
screen according to the included HTML markup and content.

1.2.2 HTML History


HTML first made an appearance in 1990-built upon the pre-existing Standard Generalized Markup Language
(SGML) - as the foundational language for the newborn World Wide Web, but it wasn’t officially defined
until 1993. It was further refined and extended with HTML 2.0, the first official HTML standard, in 1995.
Version 3.2 arrived in early 1997 with a variety of new features, and HTML 4.0 came soon afterwards around
the end of the same year.

1.2.3 Setting Up Your Development Environment

• Exploring HTML Editors: An HTML editor is a computer program for editing HTML, the
markup of a webpage. Even though the HTML web page can be created with any text editor like
notepad, specialized HTML editors can provide ease and added functionality. Some of the popular
free HTML editors are Notepad++, Sublime Text, Atom, Brackets.
• Exploring Web Browsers: Because your website users can use different browsers, you need to
make sure that your website is cross-browser compatible. For this reason, every web developer must
have major browsers like Google Chrome, Firefox, Opera, Microsoft Internet Explorer or Edge, or
Apple's Safari.
• Viewing Source Code in Browser: Underneath all the beautiful images, perfect typography, and
wonderfully placed calls to action buttons lies your webpage source code. Every web browser allows
you to access the source code of every website. You can access the HTML code of any website by
right clicking in the browser window and selecting "view page source".

1.2 Check Your Progress

Fill in the blank

1. URL stands for ________.


2. HTML is an acronym for _________.

1.3 Understanding Three Layers of Web Page: HTML, CSS, JavaScript


The web page you see in your browser is a combination of structure, style and interactivity. These jobs are
undertaken by 3 different technologies, HTML, CSS and JavaScript which your browser knows how to
interpret.

• HTML - Structure or content layer: The HTML code is the structure or content layer of the web
page. The way frames of a house generate a solid foundation, upon which the rest of the house is
built, so does a solid foundation of HTML produces a platform upon which a website can be created.
HTML structure can consist of text or images and it contains the hyperlinks that visitors use to
navigate around the web site.

• CSS - Style or presentation layer: The style or presentation layer dictates how a structured HTML
document will look to a site's visitors. This layer is defined by CSS (Cascading Style Sheets). These
files contain styles that indicate how the document should be displayed in a web browser.

• JavaScript - Behavior or interactivity layer: The behavior layer is the layer of a Web page that can
respond to different user actions or make changes to a page based on a set of conditions. For most
Web pages, JavaScript is the behavior level for the interactions on the page.

1.3 Check Your Progress

Fill in the blank

1. Three Layers of Web are ______, ______, _____.

1.4 Understanding HTML Tags

The code within an HTML file is made up of text surrounded by tags. These tags indicate where the
formatting should be used, how the layout should appear, what pictures should be placed in certain locations,
and more. For example, suppose you wanted a certain word to be italicized, like this:

Better late than never

In HTML, there’s no Italics button to click, like there is in a word-processing program. Therefore, you have
to “tag” the word that you want to be italicized. The code to turn on italics is <i>, and the code to turn italics
off is </i>. Your HTML code would look something like this:

Better <i>late</i> than<i>never</i>


Two Sided Tags: Two-sided tag encloses text between opening and closing tags, in this case <i> and </i>.
Note the forward slash in the closing tag (</i>). That slash distinguishes an opening tag from a closing tag.
With a two-sided tag, there is always a corresponding closing tag for every opening tag.

The general syntax of a two-sided element tag is

<element _name>content</element _name>

For example, the following code marks a paragraph element:

<p> Welcome to our Website</p>

Here the <p></p> tags are the starting and ending HTML tags that indicate the presence of a paragraph and
the text “Welcome to Our Website.” comprises the paragraph text.

Empty Tags or One Sided Tags: Not every tag encloses document content. Empty tags or one sided tags
are elements that are either non-textual (such as images) or contain directives to the browser about how the
page should be treated. An empty tag is entered using one of the following forms of the one-sided tag:

<element>

For example, the following <br> element, which is used to indicate the presence of a line break in the text, is
entered with the one-sided tag:

<br>

Tag Attributes
HTML attribute is a modifier of an HTML element type. All HTML elements can have attributes which give
additional information about an element.

<img src=”logo.png”>

In the above example, img tag has src (source) attribute with value logo.png file.

1.4 Check Your Progress

Fill in the blank

1. Two-sided tag encloses text between ______ and ______ tags.

1.5 Summary

Hypertext Markup Language (HTML) is the standard markup language for constructing web pages and web
applications. With Cascading Style Sheets (CSS) and JavaScript, it forms a triad of foundation technologies for
the World Wide Web.

1.6 Check Your Progress Answers


1.2

1. Uniform Resource Locator


2. HyperText Markup Language

1.3

1. HTML, CSS, JavaScript

1.4

1. opening, closing
Chapter 2

Understanding Page Structure

2.0 Objectives
2.1 Introduction
2.1.1 Specifying Document Type
2.1.2 The Head Section
2.1.3 The Body Section
2.1.4 “Hello World” Example
2.1.5 View HTML5 Page in Browser
2.1.6 HTML5 Boilerplate
2.1.7 HTML5 Validation
2.2 Adding External Files
2.2.1 Adding Stylesheet to HTML
2.2.2 Adding JavaScript Files to HTML
2.2.3 Organizing File and Folder Structure
2.3 Summary
2.4 Check Your Progress Answers

2.0 Objectives
After studying this chapter you will be able to understand
- What is doctype
- Html, head and body elements
- How to add stylesheet and JavaScript files to HTML
- How to organize web files and folder
- How to validate your html code

2.1 Introduction
In the previous chapter we briefly discussed about the HTML5 tags. In this section you will learn three most
important tags in HTML5 namely <html>, <head>, <body>.

2.1.1 Specifying Document Type

When creating an HTML5 document, the first line of the HTML 5 document should be doctype:

<!DOCTYPE html>

The DOCTYPE tag always starts with an exclamation point and is always located at the beginning of the
document, before any other tag. HTML tags are not case-sensitive, but the word DOCTYPE should usually
be uppercase. When a Web browser encounters a DOCTYPE tag, it assumes you are using HTML5. Once a
browser understands the doctype, it can render the page faster and more correctly.

2.1.2 The HTML Element


The main container for any web page is the <html> element. All content processed by the browser must be
contained within an <html>… </html> pair. Because <html> is the outermost container, it is known as the
root element. All of your HTML coding—except the DOCTYPE tag—should be placed within the two sided
<html> tag.

The HTML page so far looks like this:

<!DOCTYPE html>

<html>

</html>

2.1.3 The Head Section

Two main structural branches: the <head> and the <body> reside inside the root <html> tag . The head
section consists of information about the current document, often known as metadata. This metadata may
include the title of the document, keywords and descriptions that describe the page, author details, and
copyright statements among other information. Almost all of the content within the <head>… </head> tag
pair is hidden from immediate public view; except the <title> tag. The content in the head is not displayed in
the browser. It is meant to be applied by the external agents, such as search engine spiders.

<!DOCTYPE html>

<html>

<head>

</head>

</html>

2.1.4 The Body Section

The second structural branch within the <html> tag is the <body> tag. The body section is home to all the
content visible in the browser. The <body>… </body> tag pair is written immediately after the closing
</head> tag and before the closing </html> tag, like this:

<!DOCTYPE html>

<html>

<head>

<body>

</body>

</head>

</html>
Character Encoding

The character encoding is the standard that tells a browser how to convert your text into a sequence of bytes
when it’s stored in a file. There are many different character encodings in the world. Today, practically all
English websites use an encoding called UTF-8, which is compact, fast, and supports all the non-English
characters you’ll ever need.

<head>

<meta charset=”utf-8”>

</head>

1.1.5 Creating and Viewing HTML Page: “Hello World” Example


<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”utf-8”>

<title>HTML5:HELLO WORLD EXAMPLE</title>

</head>
<body>
<h1>Hello World</h1>
<p>Hey There</p>
</body>
</html>

2.1.6 View HTML5 Page in Browser

Open the saved HTML file in your favorite browser (double clicks on the file, or right-click - and choose
"Open with" your favorite browser).

2.1.7 HTML5 Boilerplate

The entire structure of an HTML document can be looked at as a set of nested elements in a hierarchical tree.
At the top of the tree is the html element, which marks the entire document. Within the html element is the
head element used to mark information about the document itself and the body element used to mark the
content that will show up in the web page. Thus, the general structure of an HTML file, like the one shown
below:

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”utf-8”>

<title>HTML5:HELLO WORLD EXAMPLE</title>

</head>
<body>
Body content goes here
</body>
</html>

2.1.8 HTML5 Validation

As a beginner, it is very common that you will make mistake in writing your HTML code. Incorrect or non-
standard code may cause unexpected results in how your page displayed or functions in a web browser. The
World Wide Web Consortium (W3C) has created great tools https://validator.w3.org/ to automatically check
your pages, and point out any problems/errors your code might have, such as missing closing tags or missing
quotes around attributes.

2.1 Check Your Progress

True or False

1. The first line of the HTML 5 document should be doctype


2. All content processed by the browser must be contained within an <html>… </html> pair.
3. <body> tag is one sided tag
4. the <head> reside inside the <body> tag
5. <html> is also called as root tag.

2.2 Adding External Files

You can add external files like Style sheets, JavaScript Files to HTML document.

2.2.1 Adding Stylesheet to HTML

You can add CSS file to HTML page as below:

<head>

<link rel=”stylesheet” type=”text/css” href=”style.css”>

</head>

2.2.2 Adding JavaScript Files to HTML

You can add JavaScript file to HTML page as below:

<head>

<script type=”text/javascript” src=”script.js”</script>


</head>

2.2.3 Organizing File and Folder Structure

A well-designed folder structure will help you quickly navigate to the HTML or CSS files that contain your
code. index.html is the home page main file. To store other resources you need 3 folders namely css, js and
img for storing CSS, JavaScript and Image files respectively. So the website file and folder structure look like
this:

index.html

about.html

contact.html

/css/

/js/

/img/

2.2 Check Your Progress

True or False

1. You can add external files to HTML5 document

2.3 Summary

An HTML document includes some essential components: a document type declaration (or doctype), a root
element <html> that wraps around the entire document, a head element <head> having a title and other
information about the document, and a body element <body> that contains all of the content.

2.4 Check Your Progress Answers

2.1

1. True
2. True
3. False
4. False
5. True

2.2

1. True
Chapter 3

Creating Text Elements

3.0 Objectives
3.1 Introduction
3.1.1 Line Break
3.1.2 Creating Headings
3.1.3 Applying Bold and Italic Formatting
3.1.4 Superscript and Subscript
3.1.5 Block Quotation
3.1.6 Preformatted Text
3.2 Unordered, Ordered and Definition Lists
3.2.1 Ordered Lists
3.2.2 Unordered Lists
3.2.3 Nesting Lists
3.2.4 Definition Lists
3.3 Using Links & Creating Navigation
3.3.1 Using Relative and Absolute Paths
3.3.2 Setting Link Target:
3.3.3 Linking to a Phone Number
3.3.4 Linking to an E-Mail Address
3.3.5 Creating and Hyperlinking to Anchors
3.4 Adding Images
3.5 Displaying Data with Tables
3.5.1 Table Row
3.5.2 Table Data
3.5.3 Colspan
3.5.4 Rowspan
3.5.5 Table Heading
3.6 Adding Line Break & Horizontal Line
3.7 Commenting Your Work
3.8 Summary
3.9 Check Your Progress Answers

3.0 Objectives
After studying this chapter you will be able to understand
- How to create text elements
- Build lists
- Create links
- Add images
- Structure data in tables

3.1 Introduction
To begin a new paragraph in your Web page, you use the <p> tag. Each paragraph of text should be
enclosed in a two-sided <p>. The <p> tag sets apart a text block from other elements, including other <p>
tags. A paragraph tag can have one or more sentences.

Example:

<p>Some Text Here</p>

When you hit the enter key in a word processor or your text editor, the application breaks the text you write
after it, into a new paragraph, but when you press enter key in an HTML document, the browser ignores it. If
you want to show your two sentences in two separate paragraphs, you have to clearly tell the browser to do it.
You do this with paragraph tags.

Example:

<p>First paragraph.</p>

<p> Second paragraph </p>

3.1.1 Line Break

To create a line break without officially starting a new paragraph, use the line break tag: <br>. This is a one-
sided tag placed within a paragraph, at the end of each line, like this:

Example:

<p>First line<br>

Second line </p>

3.1.2 Creating Headings

Headings in webpages work the same manner as they do in printed documents - they separate text into
sections. The HTML standard defines six levels of headings, <h1> through <h6>, each one gradually smaller
in font size. The heading levels indicate relative sizes; the higher the heading number, the smaller the size.
<h1> has the large font size and <h6> has the smaller font size.

Example:

<h1>This is heading 1</h1>

<h2>This is heading 2</h2>

<h3> This is heading 3</h3>

<h4> This is heading 4</h4>

<h5> This is heading 5</h5>

<h6> This is heading 6</h6>


3.1.3 Applying Bold and Italic Formatting

Making use of bold and italic styles are two ways of making text stand out and draw in attention. For simple
boldface and italics, use the <b> tag or the <i> tag, correspondingly. Both are two-sided tags that enclose the
text to be formatted.

Example:

<p><b>John Smith</b><i>Welcome</i>to our site</p>

3.1.4 Superscript and Subscript

Superscript formatting makes text smaller and raises it off the baseline. You’d typically use superscript <sup>
to format exponents in arithmetic equations (for example, the 2 shown in X2+1). You can also use
superscript to format ordinal numbers (such as 1st, 2nd, and 3rd) to make your page look more refined.
Subscript <sub> makes text smaller and moves it below the baseline. The most common use for subscripts is
in chemical formulas (for example, H 2 SO 4 ).

Example:

<p>1<sup>st</sup></p>

<p>H<sub>2</sub>SO<sub>4</sub></p>

3.1.5 Block Quotation

The <blockquote> tag specifies a section that is quoted from another source. Browsers usually indent
<blockquote> elements.

Example:

<blockquote>Our greastsst weakness lies in giving up. The most certain way to succeed is always to try just
one more time. </blockquote>

3.1.6 Preformatted Text

The <pre> tag describes preformatted text. Text in a <pre> element is shown in a fixed-width font (usually
Courier), and it maintains both spaces and line breaks.

Example:

<pre>

Text in a pre element

is displayed in a fixed-width

font, and it preserves

both spaces and line breaks


</pre>

3.1 Check Your Progress

True or False

1. <br> tag is used for line break.


2. <h1> has the smaller font size and <h6> has the larger font size.
3. <b> tag and the <i> tag are two sided tags

3.2 Unordered, Ordered and Definition Lists

HTML supports three types of lists: 1) ordered lists, 2) unordered lists, and 3) definition lists.

3.2.1 Ordered Lists

Ordered lists are designed for items that follow some defined sequential order, such as items organized
alphabetically or numerically. An ordered list is marked using the ol (ordered list) element with each list item
marked using the li element. The standard layout is

Example:

<ol>

<li>Paris</li>

<li>London</li>

<li>New York</li>

</ol>

</ol>

Output:

1. Paris
2. London
3. New York
Note that because both the ol and li elements are considered grouping elements, each list item will appear, by
default, on a new line in the document unless a different style is applied to those elements.

3.2.2 Unordered Lists


Unordered lists are used for lists in which the items have no sequential order. The layout for an unordered list
is similar to that used with ordered lists apart from that the list items are grouped within the following ul
(unordered list) element and get bullet points instead of numbers.

Example:

<ul>

<li>Paris</li>

<li>London</li>

<li>New York</li>

</ul>

Output:

1. Paris
2. London
3. New York
3.2.3 Nesting Lists

You can nest lists within one another. In the next example, we have a bulleted list embedded within a
numbered list. Notice how this nested list was built. The bulleted sublist (the <ul> tag) is put within one of
the <li> tags within the numbered <ol> list.

Example:

<ol>

<li>France</li>

<li>England:

<ul>

<li>London</li>

<li>Birmingham</li>

<li>Leeds</li>

<li> Glasgow</li>
</ul>

</li>

<li>USA</li>

</ol>
Output:

1. France
2. England
• London
• Birmingham
• Leeds
• Glasgow
3. USA

3.2.4 Definition Lists

A third type of list is the definition list made up of a list of terms and matching definitions. The definition list
is grouped by the dl (definition list) element, the terms are noted with the dt (definition term) element, and
the definition (s) associated with each term is noted by the dd element. The standard structure is

Example:

<dl>

<dt>HTML</dt>

<dd>Hypertext Markup Language</dd>

<dt>CSS</dt>

<dd>Cascading Style Sheet</dd>

</dl>

3.2 Check Your Progress

True or False

1. Unordered lists have sequential order


2. Definition list is made up of a list of terms and matching definitions

3.3 Using Links & Creating Navigation

Links are one of the most significant elements in HTML. Without the ability to link from one document to
another, the Web wouldn't be the Web. The “H” in “HTML,” hypertext, becomes meaningless without the
concept of linked documents. Linking the Web begins with the <a>, or anchor element, one of the oldest
elements.

Hypertext is designed by enclosing content within a set of opening and closing <a> tags in the following
structure:
Example:

<a href=”http://google.com”>Google</a>

3.3.1 Using Relative and Absolute Paths

Paths that include a complete address that everyone can use to get to that page are called absolute paths.
Absolute paths are very reliable, but they are also long and awkward to type.

Example:

<a href=”http://www.example.com/index.html”>Example Site</a>

When you are linking to files in the same website as the link itself, you do not need to include the full path to
the file; you can simply provide its name. When the file is in the same folder, you need only supply the file
name. For example, if the index.html and about.html pages of the web site are in the same folder, in the
index.html file, you can refer to about.html like this:

Example:

<a href=”about.html”>About Us</a>

This is called a relative path, because the destination file is relative to the current file’s location. Relative paths
make it easier to develop and test your website in a different file location than the one where it will eventually
be stored.

You can link to the file inside subfolder as below:

Example:

<a href=”about/history.html”>History</a>

You can also create a link to a file that is up one level (a parent folder) with a relative reference as below:

Example:

<a href=”../contact.html”>Contact</a>

3.3.2 Setting Link Target:

By default, a hyperlink opens the linked page in the same browser tab. Which means the new page replaces
the previous page. Generally this is fine, but in some instances you might want the hyperlink to open in a new
tab. For example, maybe you want to endorse that visitors check out a page on another site, but you don’t
want them to leave your site. To direct the hyperlink to open a page in a new tab, add the attribute
target=“_blank” to the <a> tag.

Example:

<a href=”http://www.example.com/about.html” target=”_blank”>About</a>


3.3.3 Linking to a Phone Number

Due to the increased use of mobile phones to visit the web, we need to include link to contact phone number
of the organization. Clicking on the link brings up the user’s phone app with the number already entered,
making it much easier and more convenient to call the business or organization. You can use tel: followed by
telephone number without space to create telephone link.

Example:

Call: <a href=”tel:1234567890”>(123) 456-7890</a>

3.3.4 Linking to an E-Mail Address

Many websites use e-mail to allow users to communicate with a site’s owner, sales representative, or technical
support staff. You can turn an e-mail address into a hypertext link using the URL:

Example:

<a href=”mailto:contact@example.com”> contact@example.com </a>

Clicking the link opens the user’s e-mail program with the e-mail address automatically inserted into the “To”
field of a new outgoing message.

3.3.5 Creating and Hyperlinking to Anchors (On the same page)

An anchor is a marker within an HTML document, similar to a bookmark in a Word document. You define a
specific location in the document with an anchor name, and then you can hyperlink directly to that anchor.
Anchors are most valuable in lengthy documents with multiple sections. They give a means for users to jump
straight to whatever section they want rather than having to read or scroll through the entire document.

For example, you have a heading that reads Services, and you have an anchor point with name="services". To
refer to the anchor point, include its name in the href= attribute and precede the anchor name with a pound
(hash) sign (#).

Example:

Link at the top of the page:

<a href=”#services”>View The Services </a>

Section on the same page to be linked:

<a name=”services”> Services </a>

3.3 Check Your Progress

True or False

1. Paths that include a complete web address are called absolute paths.

3.4 Adding Images


Every image used on an HTML page is a separate file. To incorporate these files into your source code, we
need the <img> tag. The <img> tag is a single or empty HTML tag, which means no closing tag is required.

Example:

<img src=”images/logo.png” width=”400” height=”175” alt=”Company Logo”>

The <img> tag is a single or empty HTML tag, which means no closing tag is required. The primary attribute
of an <img> tag is src, short for source. The src value contains the path to the desired graphic file. As with
links, the path can be either relative to the current page, like the preceding example, or absolute, like this one:
http://www.example.com/images/logo.gif

Strictly speaking, browsers don’t need the width or height attributes to render the image; they can detect the
size if those values are not present. The final attribute in the example code, alt, is short for alternative text. If,
for whatever reason, the browser is not able to display the image, the alternative text is shown.

The three most widely used formats on the Web are GIF, PNG, and JPEG. Current browsers can view all
three image formats. The JPEG format is good for color photographs because it handles large amounts of
color and it compresses well. The PNG and GIF formats are often used when you’re saving files like logos
with transparency. JPEG images are not transparent.

3.4 Check Your Progress

True or False

1. <img> is a two sided tag.

3.5 Displaying Data with Tables

If you’ve used a word-processing program before, you’re most likely already familiar with the task of creating
tables. A table is a grid of rows and columns, the intersections of which form cells. Every cell is a distinct
area, into which you can place text, graphics, or even other tables. HTML handles tables very well, and you
can use them to set up and present complex data to your site visitors.

3.5.1 Table Row

Tables are composed of cells organized into rows and columns. In HTML, you mark up tables one row at a
time using the <tr> element which is short for “table row.”

3.5.2 Table Data

The <td> element, the workhorse of any HTML table, represents an individual cell in a data table. The
element’s name, which is short for “table data,” gives you a hint of its expected content.

Example:

<table>
<tr>

<td>Contect</td>

</tr>

</table>

3.5.3 Colspan

The colspan attribute accepts a positive integer and instructs the browser to create a cell that spans as many
columns of the table

Example:

<table>

<tr>

<td colspan=”2”> Two Column Contect</td>

</tr>

<tr>

<td>One</td>

<td Two </td>

</tr>

</table>

3.5.4 Rowspan

Similar in usage to the colspan attribute, the rowspan attribute accepts a positive integer as its value. The
higher the specified value, the more rows your cell will span.

Example:

<table>

<tr>

<td rowspan=”2”> Product Name</td>

</tr>

<tr>

<td> Price</td>
<td Quantity </td>

</tr>

<tr>

<td>50</td>

<td 2 </td>

</tr>

</table>

3.5.5 Table Heading

The <th> tag defines a header cell in an HTML table. The text in <th> elements are bold and centered by
default.

Example:

<table>

<tr>

<th>Product></th>

<th>Quantity></th>

</tr>

<tr>

<th>Mobile</th>

<th>19</th>

</tr>

<tr>

<th>Laptop<th>

<th>27</th>

</tr>

</table>
3.5 Check Your Progress

True or False

1. <th> stands for Table Heading

3.6 Adding Horizontal Line

Horizontal lines can be valuable as dividers between sections of text in a Web page. By default, the line runs
the whole width of the browser window, is two pixels in height, and is black. You can change these
characteristics by applying attributes within the tag.

Example:

<hr>

3.6 Check Your Progress

True or False

1. <hr> tag is used for vertical line

3.7 Commenting Your Work

Commenting is a way to tell the browser to ignore certain parts of text that you include within the body of
code. Comments are for the human, not the machine. They help you and others understand your code when
it’s time to revise the code. You can also use commenting to comment out portions of your code for testing
and debugging.

In HTML any text enclosed by an opening <!— tag, and a closing --> tag is invisible to the browser.

Example:

<!—

This is a comment

3.7 Check Your Progress

True or False

1. Content inside HTML5 comments remains hidden from users

3.8 Summary
<p> tag is used to add text paragraph in HTML page. Six levels of headings, <h1> to <h6>, are used to add
titles. You can use <b> and <i> tag to make text bold and italic respectively. HTML supports three types of
lists - ordered list, unordered list and definition list. <a> or also called as anchor tag is used to create web
links. You can add images to web site with <img> tag and data tables with <table> tag.

3.9 Check Your Progress Answers

3.1

1. True
2. False
3. True
4. True

3.2

1. False
2. True

3.3

1. True

3.4

1. False

3.5

1. True

3.6

1. False

3.7

1. True
Chapter 4

HTML: Working with Web Forms

4.0 Objectives

4.1 Introduction

4.1.1 Adding Input Boxes

4.1.2 Using Textarea

4.1.3 Using Label

4.1.4 Working with Radio Buttons

4.1.5 Offering Checkbox Options

4.1.6 Implementing Select List

4.1.7 Adding Buttons

4.1.8 Form Processing

4.2 Summary

4.3 Check Your Progress Answers

4.0 Objectives

After studying this chapter you will be able to understand

- How to create basic form

- Form elements like input, textarea, radio button, checkbox, select box etc

- Form submission

- Form processing

4.1 Introduction

You can insert a form anywhere in the body of an HTML document. All basic web forms function in the
same manner. The user fills in some details and then clicks a button. At this stage, the server gathers all the
data that the user has entered and transmits it back to the web server.

A form is basically made of four parts:

• The <form> tag


• Form controls, such as the <input> tag
• Labels, which identify the form elements
• A trigger, typically a button form element, that submits the form

A simple form, in code, would look like this:

<form action=”submit.php” method=”post”>

<label for=”fullName”>Name:</label>

<input type=”text” name=”fullName”>

<input type=”button” value=”Submit”/>

</form>

Form Attributes

• action: Specifies the URL of the form handler, which is the script or application that will process the
submitted form data.
• method: Specifies which HTTP method will be used to submit the form data, either get or post. The
method defaults to get if this attribute is missing.
• enctype: Specifies the type of encoding to use when the form is submitted, one of three possible
values: application/x-www-form-urlencoded (the default), multipart/form-data (if the submitted form
will include files uploaded via an input type="file" control), or text/plain which performs no
additional encoding.

4.1.1 Adding Input Boxes

Most popular form controls are instances of the input element, with each type of input control showed by a
corresponding type attribute. The input element is styled as inline by default so many can appear on the same
line.

Text

You create a regular text box using a single-sided <input> tag with a type=“text” attribute:

Example:

<input type=”text”>

Each control within a form must have a unique name, expressed with the name attribute. For example, to
name a particular text box phone:

<input type=”text” name=”phone”>


You can specify a width for the text box with the size attribute. The default width is 20 characters.

<input type=”text” name=”phone” size=”30”>

You can also specify a maximum length for the text string that users enter into the text box.

<input type=”text” name=”phone” size=”30” maxlength=”100”>

In HTML5, you can require users to fill out a field before they submit the form

<input type=”text” name=”phone” size=”30” maxlength=”100” required>

Email

HTML5 supports a new input field type e-mail address. Use the attribute type=”email” instead of
type=”text” to define a field designed to collect e-mail addresses.

<input type=”email” name=”email-address”>

Password

This control is similar to a text field. The input type="password" defines a password field. The characters in a
password field are masked (shown as asterisks or circles).

<input type=”password” name=”password”>

Url

The input type="url" is used for input fields that should contain a URL address:

<input type=”url” name=”website-address”>

Date

The input type="date" is used for input fields that should contain a date. A date picker pops up when you
enter the input field.

<input type=”date” name=”dob”>

Number

The input type="number" defines a numeric input field. You can use the min and max attributes to add
numeric restrictions in the input field:

<input type=”number” name=”quantity” min=”1” max=”5”>

Range

The input type "range" can be displayed as a slider control.

<input type=”range” name=”points” min=”0” max=”10”>


Time

The input type="time" allows the user to select a time (no time zone):

A time picker might pop-up when you enter the input field.

<input type=”time” name=”time”>

4.1.2 Using Textarea

You create a multi-line text area by using a two-sided <textarea> tag containing a rows attribute that specifies
the number of lines of text that the box should accommodate.

<textarea name=”comments” rows=”5”></textarea>

You can also include a columns attribute that specifies how many characters (each character represents a
single column) wide the text area will be. The default is 40 characters.

<textarea name=”comments” rows=”5” cols=”60”></textarea>

The columns attribute affects only the size of the box, not the maximum number of characters that can be
entered. You can use the maxlength attribute to limit the number of characters a user can enter.

Placeholder Text

By default, text boxes and text areas are blank when the form loads. You can in addition place either default
or placeholder text in them. Placeholder text is "dummy" text that shows up as a prompt within the text box
but disappears when the user types something else there.

<input type=”text” name=”fname” placeholder=”First Name”>

4.1.3 Using Label

The HTML <label> element represents a caption for an item in a user interface. The “for” attribute specifies
which form element a label is bound to.

<label for =”name”>Name</label>

<input type=”text” name=”name”>

4.1.4 Working with Radio Buttons

<input> elements of type radio are generally used in radio groups - collections of radio buttons explaining a
set of related options. Only one radio button in a given group can be selected at the same time. Radio buttons
are commonly rendered as small circles, which are filled or highlighted when selected.

<input type=”radio” name=”gender” value=”male” id=”male”>

<label for=”male”>Male</label>

<input type=”radio” name=”gender” value=”female” id=”female”>


<label for=”female”>Female</label>

4.1.5 Offering Checkbox Options

<input> elements of type checkbox are rendered by default as square boxes that are checked (ticked) when
activated, like you might see in an official government paper form. They allow you to select single values for
submission in a form. It is used for yes no type of questions.

Example:

<input type=”checkbox” name=”subscribe” value=” Subscribe”>

4.1.6 Implementing Select List

Check boxes are good for yes/no questions, and option buttons are suitable when there are a few options to
select from, but what if you have a dozen or more choices? The <select> element is used to create a drop-
down list. The <option> tags inside the <select> element define the available options in the list. A single-line
selection control, generally called a drop-down menu, will display the selected option when in its collapsed,
inactive state, with a small arrow at one end as a visual cue that the control can be expanded.

Example:

<select name=”colors”>

<option value=”red”>Red</option>

<option value=”green” selected>Green</option>

<option value=”blue”>Blue</option>

</select>

4.1.7 Adding Buttons

You will require including a Submit button on the form so your site visitors can send the information to you.
Submit refers to the button’s function, not the text that appears on the button face. The default button text is
Submit, but you can use a value attribute to show different text on the button.

<input type=”submit” value=”Get A Quote”>

You can also include a Reset button on the form, which allows the user to clear all the fields. Again, use the
value attribute to change the text on the button:

<input type=”reset” value=”Clear”>

4.1.8 Form Processing

The specific form processing script to be used is identified with the action attribute in the <form> tag

Example:
<form action=”submit.php” method=”post”>

</form>

4.1 Check Your Progress

True or False

1. You create a single line text area by using textarea tag


2. <label> element represents a caption for form element
3. Only one radio button in a given group can be selected at a time.
4. The <select> element is used to create a drop-down list.

4.2 Summary

Getting feedback from your Web site’s users can be a useful way of assessing your site’s success, and it can
help you build a customer or subscriber database. For example, a business could collect the addresses, phone
number and email addresses of people who are interested in receiving product samples, e-mail newsletters, or
notifications of special offers. You can create form with <form> tag and add fields like input, checkbox,
radio button, select options, submit button.

4.3 Check Your Progress Answers

4.2

1. False
2. True
3. True
4. True
Chapter 5

Organizing Page Structure

5.0 Objectives

5.1 Introduction

5.2 The Value of Structure: Semantic Elements

5.2.1 The Header Container: <header> Tag

5.2.2 The Footer Content Container: <footer> Tag

5.2.3 The Navigation Container: <nav> Tag

5.2.4 The Main Content Container: <main> Tag

5.2.5 The Page Division Container: <section> Tag

5.2.6 The Independent Content Container: <article> Tag

5.2.7 The Related Content Container: <aside> Tag

5.3 Few More Semantic Elements

5.3.1 Adding Contact Information with <address> Tag

5.3.2 The Image Container: <figure> Tag

5.3.3 The Graphics Container: <canvas> Tag

5.3.4 Embedding Audio and Video with <audio>, <video> Tags

5.3.5 The Vector Based Image Container: <svg> Tag

5.4 Summary

5.5 Check Your Progress Answers

5.0 Objectives

After studying this chapter you will be able to understand

- What are semantic elements?

- Distinction between different semantic elements and when to use each one

5.1 Introduction
The HTML Content Division element (<div>) is the popular container for flow content. It has no impact on
the content or layout until styled using CSS. As a "pure" container, the <div> element does not naturally
represent anything. Rather, it's used to group content so it can be very easily styled using the class or id
attributes.

Example:

<div>

<h1>Title</h1>

<p>Some Content</p>

<ul>

<li>List Item 1</li>

<li>List Item 2</li>

<li>List Item 3</li>

</ul>

<div>

<img src=”images/box.jpg” alt=”box”>

</div>

</div>

5.1 Check Your Progress

True or False

1. <div> tag stands for division element

5.2 The Value of Structure: Semantic Elements

Semantic markup brings out meaning to the web page rather than just presentation. For example, a <article>
tag implies that the enclosed text is an article. This is both semantic and presentational, mainly because people
know what articles are and browsers know how to display them. On the flip side of this picture, tags like <b>
and <i> are not semantic, because they define only how the text should look (bold or italic) and do not
furnish any extra meaning to the markup.

5.2.1 The Header Container: <header> Tag


The <header> element is used for introductory or navigational content for a section of a document. It
frequently appears at the top of a section, but it doesn’t have to; calling it a “header” may imply a position at
the top, but it’s an introduction to the section, and can in fact used anywhere inside that section. The term
“header” also generally refers to a website’s overall masthead — where you would generally find the company
name/logo of the website, some navigation links, maybe a search form, and so on.

Example:

<header>

<a href=”index.html”><img src=”logo.png” alt=”Company Logo”></a>

<ul>

<li><a href=”index.html”>Home</a></li>

<li><a href=”about.html”>About</a></li>

<li><a href=”services.html”>Services</a></li>

<li><a href=”contact.html”>Contact</a></li>

</ul>

</header>

5.2.2 The Footer Content Container: <footer> Tag

An opposite number to the header element, the <footer> element includes extra information about its parent
sectioning element, which include author contact information, related links, copyright or licensing,
supplemental navigation, and disclaimers. It commonly shows up at the end of a section but that’s not a
requirement. Just like header, the name “footer” doesn’t actually refer to a location-this is footer content by
nature, not just by position.

Example:

<footer>

<p>Copyright &copy; . All Rights Reserved.</p>

</footer>

5.2.3 The Navigation Container: <nav> Tag

A <nav> element consists of navigation - a group of web links that lead to other pages on a website, or to
sections of the current page. In a sense, all links are navigation, but don’t use <nav> for every collection of
links; the nav element is designed only for main blocks of navigation. Most websites have a header or
masthead, a dominant banner that features the site name, logo, and generally the primary navigation for the
website. You can use <nav> element in the masthead as below:

Example:
<header class=”masthead”>

<a href=”index.html”><img src=”logo.png” alt=”Company Logo”></a>

<nav class=”site-navigation”>

<ul>

<li><a href=”index.html”>Home</a></li>

<li><a href=”about.html”>About</a></li>

<li><a href=”services.html”>Services</a></li>

<li><a href=”contact.html”>Contact</a></li>

</ul>

</nav>

</header>

5.2.4 The Main Content Container: <main> Tag

The HTML <main> element signifies the dominant content of the <body> of a document. The main
content area is made up of content that is directly related to the core topic of a document.

Example:

<main>

<h1>Title</h1>

<p>Some Content</p>

</main>

5.2.5 The Page Division Container: <section> Tag

The HTML <section> element represents a standalone section — which doesn't have a more specific
semantic element to represent it.

Example:

<section>

<h1>Title</h1>

<p>Content</p>

</section>
5.2.6 The Independent Content Container: <article> Tag

The <article> element is just like the section element, although with a more enhanced definition. According
to the HTML5 specification, an article element means “a self-contained composition in a document, page,
application, or site and that is, in principle, independently distributable or reusable, e.g. in syndication.” Put
simply, an article element’s content should stand on its own. It could be a blog entry, a comment, a forum
post, a letter, a review, a poem, a short story, or indeed an article. Following is a good example of a concise,
self contained article, complete with title, author byline, and date.

Example:

<article>

<h1>Stories of Great Inventors Fulton, Whitney, Morse, Cooper, Edison</h1>

<h2>ROBERT FULTON</h2>

<p>This story is about a giant. Do you believe in them?...</p>

<p>Author Name: <strong>Hattie E. Macomber</strong></p>

<p>Published: 1897</p>

</article>

5.2.7 The Related Content Container: <aside> Tag

Another new element in HTML5 <aside> represents - content that works with and improves the main
content, but isn’t an essential part of it. It is optional information that you could very easily remove without
doing harm to the reader’s understanding of the primary content. An aside element might contain extra
commentary, a glossary of terms, background information, a collection of related links, a pull quote, or even
advertising. The kind of secondary content you would use in an aside element is often called a sidebar in
publishing, and that term is prevalent in web design as well, but the words “sidebar” and “aside” don’t really
mean a position on the left or right side of the main content. Use aside properly and don’t get stuck on the
name.

Example:

<aside>

<h3>Related Posts</h3>

<ul>

<li>Article 1</li>

<li>Article 2</li>

<li>Article 3</li>

</ul>
</aside>

5.2.8 Adding Contact Information with <address> Tag

The HTML <address> element implies that the enclosed HTML presents contact information of the
organization. The contact information presented by an <address> may include any type of contact
information needed, such as physical address, URL, email address, phone number, social media handle,
geographic coordinates, and so forth. It can contain the name of the person or organization of which the
contact information refers.

Example:

<address>

Tilak Maharashtra Vidyapeeth<br>


Vidyapeeth Bhavan, Gultekadi, Pune 411 037<br>
Website: www.tmv.edu.in<br>
Email: registrar@tmv.edu.in

</address>

5.2.9 The Image Container: <figure> Tag

A new addition to HTML5, the figure element represents an image, video, quotation, code listing, or some
other content, along with an optional caption.

Example:

<figure>

<img src=”images/product.png” alt=”Our Product”>

<figcaption>Product Name</figcaption>

</figure>

5.2.10 The Graphics Container: <canvas> Tag

The canvas element creates an empty drawing area for dynamically generated imagery - a figurative blank
canvas. The markup is incredibly simple:

Example:

<canvas></canvas>

The canvas element creates 300 pixels wide by 150 pixels high box by default, but you can supply your own
dimensions with the optional width and height attributes.

<canvas id=”myCanvas” width=”460” height=”300”></canvas>


5.2.11 Embedding Audio and Video with <audio>, <video> Tags

The addition of the <video> and <audio> tags in HTML5 makes it easy to deliver and play video and audio
files. In the past, developers and designers have mostly set up pages to play video and audio on the website
using Adobe Flash Player. This required that the end user has the Adobe Flash player installed to play the
audio and video file.

The HTML Video element (<video>) embeds a media player which supports video playback into the
document. It may contain one or more video sources, represented using the <source> element: the browser
will choose the most suitable one.

Example:

<video width=”400” controls>

<source src=”mov.mp4” type=”video/mp4”>

<source src=”mov.ogg” type=”video/ogg”>

<!--comment for outdated browsers -->

Your browser does not support HTML video.

</video>

The HTML <audio> element is used to embed sound content in documents. It may contain one or more
audio sources, represented using the src attribute or the <source> element: the browser will choose the most
suitable one.

Example:

<audio controls=”controls”>

<source src=”audio-file.ogg” type=”audio/ogg”>

<source src=” audio-file.mp3” type=”audio/mp3”>

<!--comment for outdated browsers -->

Your browser does not support audio element.

</audio>.
5.2.12 The Vector Based Image Container: <svg> Tag

SVG stands for Scalable Vector Graphics. It is used to define graphics for the Web. The HTML <svg>
element is a container for SVG graphics. It has several methods for drawing paths, boxes, circles, text, and
graphic images.

Example:

<svg width=”100” height=”100”>

<circle cx=”50” cy=”50” r=”40” stroke=”green” stroke-width=”4” fill=”yellow”/>

</svg>

5.2 Check Your Progress

True or False

1. Semantic markup brings out meaning to the web page.


2. <section> element represents a standalone section.
3. An <aside> element contains main content of the site.
4. The canvas element creates an empty drawing area.

5.3 Summary

Semantic markup brings out meaning to the web page. The <header> element is used for introduction of a
document. Footer element commonly shows up at the end of a section or document. A <nav> element
consists of navigation or web links. Element <address> can be used for contact information. Some of the
newly added graphic and media related elements are <canvas>, <figure>, <video>, <audio>, <svg>.

5.4 Check Your Progress Answers

5.1

1. True

5.2

1. True
2. True
3. False
4. True
Chapter 6

CSS: Cascading Style Sheets

6.0 Objectives

6.1 Introduction

6.1.1 History of CSS

6.1.2 3 Methods of Adding CSS to HTML File

6.2 CSS Rule Structure: CSS Syntax

6.2.1 Using Different Units of Measurement

6.2.2 Block Level vs Inline Elements

6.2.3 Adding CSS Comments

6.2.4 Code Formatting

6.2.5 Validating CSS Code

6.3 Summary

6.4 Check Your Progress Answers

6.0 Objectives

After studying this chapter you will be able to understand

- What is CSS

- History of CSS

- Syntax of CSS

- Difference between block level and inline element

- How to validate your CSS code

6.1 Introduction

Building a website with HTML (Hypertext Markup Language) is only part of the story. HTML controls the
structure of a web page, using tags such as <img> for images, <p> for paragraphs, and <a> for link
elements. This structural role has become even more important with the arrival of semantic elements, such as
<header>, <footer>, <article> and <nav>, in HTML5. But HTML mentions nothing about how the page
should look. That is the role of Cascading Style Sheets (CSS).
Cascading Style Sheets (CSS) is a simple language defining styles, which can be applied to HTML. Where
HTML represents the structure of a web page, CSS represents its presentation. Cascading Style Sheets - CSS
for short, provide you total control over the layout and design of your web pages. Using CSS, you can spice
up your site’s text with eye-catching headlines, borders, and drop caps, just like the ones in shiny magazines.
You can also organise images with accuracy, create columns and banners, and spotlight your links with
compelling rollover effects. You can even make components fade in or out of the view, make a button
gradually transform colors when a visitor moves mouse over it, or move items around the web page.

An international community also known as the World Wide Web Consortium (W3C) creates and maintains
the CSS specifications that specify and standardize the method in which people should write the CSS
language and browsers should execute it.

The Role of CSS:

Before CSS, almost all of the presentational features of HTML documents were added in the HTML markup;
all font styles, colors, background styles, borders, element alignments had to be clearly described, within the
HTML. Due to this, development of huge web sites, in which fonts and color information were often added
to each and every page, became a lengthy and costly process. CSS eliminate these issues, by enabling web
designers to move all of that formatting information to a distinct style sheet generating considerably cleaner
HTML markup.

Advantages of Using CSS:

• Consistency and Efficiency: By making one change to our website's CSS Style Sheet, you can
automatically make it available to every page of your website. It also ensures that all your web pages
have consistent styling throughout your site.
• Pages load faster: When you use CSS you do not need to style HTML tags every time. You can just
write one CSS rule of a tag and apply it to all the occurrences of that tag in your website. Less code
simply means faster load time.
• Easy Maintenance: CSS simplifies website maintenance and give web designers’ one file to manage
all the styling.
• Mobile Responsive: CSS allows content to be optimized for more than one type of device. Using
CSS, the same HTML document can be presented in different viewing layouts for different rendering
devices such as computer screen, smart phones, tablets etc.

6.1.1 History of CSS:

CSS was first recommended by Hakon Wium Lie on October 10, 1994 and managed through a group of
people within the W3C (World Wide Web Consortium) called the CSS Working Group. The World Wide
Web Consortium or W3C is a group that makes suggestions about how the Internet works and how it should
develop.

CSS Versions
CSS level 1 (CSS1) was officially introduced in 1996, and included properties like typeface and emphasis color
of text, backgrounds, and other text attributes such as spacing between words, letters, and lines of text.

CSS level 2 (CSS2) standard was designed by the W3C and released as a recommendation in 1998. It added
properties for positioning that allowed CSS to be utilized for page layout.

The CSS level 3 (CSS3): First drafts were published in 1999. CSS3 adds presentation-style properties, allowing
us to effectively build presentations from HTML documents. CSS3 is divided into 50 plus CSS modules. Last
working draft was released in 2016. All the major browsers now support majority of the CSS3 features.

CSS4: First draft of CSS4 was released in 2017. It is still under development stage.

6.1.2 3 Methods of Adding CSS to HTML File:

There are 3 ways to add CSS styles to the website: You can 1) use internal CSS and include CSS rules in
<head> section of the HTML document, 2) use inline CSS to apply rules for specific element in HTML file
or 3) link to an external CSS file which contains all CSS rules (Recommended method)

Internal CSS

Internal styles are added within the <style> element, within the <head> section of an HTML page. The
<style> tag is part of HTML, and not CSS. But its job is to inform the web browser that the data included
within the <style> tags is CSS code. To create a <style> block, you write the style rules in precisely the same
way as in an external style sheet, and use them in a pair of HTML <style> tags. Using an HTML <style>
block restricts the style rules to the current page, so this technique should not be employed for styles that
need to be applied to multiple pages.

Example:

<head>

<style>

body{

background-color: red;

</style>

</head>
Inline CSS

Inline css style goes in the opening tag of an HTML element, so it is applicable to that element alone. To
make use of it you can simply add a "style" attribute to the HTML element. The style attribute can consist of
any CSS property. Applying CSS this way is not recommended, as each HTML tag requires to be styled
separately. Organizing your website may become too complicated if you only use inline CSS. However, it can
be beneficial in some situations, like email newsletters.

Example:

<h1 style=”background-color: red;”>This is a heading</h1>

External CSS

This is the most popular and powerful way of using CSS. The styles in external style sheets impact all pages to
which they’re connected. Primarily an external style sheet is implemented for an entire site or subsection of a
site, making it easy to update multiple pages by editing only one file. An external style sheet is simply a text
file comprising all our CSS rules having file extension of .css. This is the most popular method of using CSS.
With an external style sheet, you can alter the look of an entire website by editing just one file! An external
style sheet can be anywhere within your website, but the common practice is to place all style sheets in a
dedicated folder called styles or css. You attach an external style sheet in the <head> section of your web
page with a <link> tag. A <link> tag looks like this:

Example:

<head>

<link rel=”stylesheet” type=”text/css” href=”css/style.css”>

</head>

6.1 Check Your Progress

Fill in the blank

1. CSS stands for ______________.


2. 3 Methods of Adding CSS to HTML File are ______, ______ and ______.

6.2 CSS Rule Structure: CSS Syntax

The CSS syntax is composed of a set of rules. These rules have 2 parts: a selector and a declaration block.

1. Selector: The selector pertains to the HTML element you want to style.
2. Declaration Block: The declaration block starts with an opening brace ({) and ends with a closing
brace (}).
• Declaration: Between the opening and closing braces of a declaration block, you add one or
more declarations, or formatting commands. Every declaration has two parts, a property and a
value. A colon separates the property name and its value, and the whole declaration ends with a
semicolon.
1. Property: CSS offers you a number of formatting options, known as properties. A property
is a word-or a few hyphenated words - implying a particular style effect. Most properties
have simple names like font-size, margin-top, and text-align.

2. Value: Every given property has a value that indicates how we wish to change the features
of the property. Some properties have a set list of values that you can select from. Others
allow you to define the value yourself.

Note: You don’t need to write a style on a single line, as in the picture, you can write it as shown below:

Example:

p{

color: blue;

font-size:16px;

In the above example, p is the selector, the element we want to style.

Following is the declaration block.

color: blue;

font-size:16px;

The property “color” has “blue” value. Every property-value pair ends with semicolon.
6.2.1 Using Different Units of Measurement

Units of measurement generally used with printed materials - picas, points, inches, and so on, don’t function
well on web pages because you can’t anticipate how they’ll look from one monitor to the next. CSS supports
a number of, units of measurements consisting of absolute units such as inches, centimeters, pixels etc., and
relative measures including percentages, em and rem units.

If you don’t define a text size using CSS, a web browser falls back on its pre-programmed options. Generally
in most browsers, text inside a paragraph tag is displayed 16 pixels tall-that’s known as the base text size.

Absolute Units

Absolute units are fixed and don’t relate to one another, meaning they aren’t inherited. For example: pixel

Relative Units

Relative units are those that relate to each other, being inherited from their parent element. For example
percentage, em and rem

Here are some of the important units of measurements

Pixel: Pixel values are the simplest to understand, since they’re totally independent from any browser
options. When you define, for example, a 36-pixel font size for an <h1> tag, the web browser shows text
that’s 36 pixels tall, period! Web designers enjoy pixel values since they offer constant text sizes across distinct
types of browsers. The CSS code looks like this:

font-size :36px;

Keywords: CSS provides seven keywords that let you assign a size that’s relative to the base text size: xx-
small, x-small, small, medium, large, x-large, and xx-large. The CSS code looks like this:

font-size :large;

Percentage: Like keywords, percentage values adjust text in relationship to the font size defined by the
browser, but they give you much finer control than just large, x-large, and so on.

Ems: The W3C defines an em unit as “the computed value of the font-size property of the element on which
it is used.”

div{

font-size:20px;

width:4em;

height:4em;

}
In the above example, width and height will be 20x4 =80px

Rem: CSS Level 3 introduces a new unit called Rem (Root em). The W3C is aware of the troubles when
working with inherited values and em, so it released rem. Rem inherits its value only from the root element,
that being the <html> element. Therefore, in the rem unit, each element inherits the same font size from the
root (16px).

div{

font-size:20px;

width:4em;

height:4em;

When you use rem, it does not matter what font size you use for the element. The browser’s default font size
of <html> is 16px hence the width and height in above example will be 16x4=64px

6.2.2 Block Level vs Inline Elements

A block-level box or element - for example, a <div>, heading <h1>, or paragraph tag <p>, takes up all
available horizontal space, beginning on a line of its own and forcing following elements down onto a new
line. Common block level elements are: Paragraphs <p>, Headers <h1> through <h6>, Divisions <div>,
Lists and list items <ol>, <ul>, and <li>, Forms <form>.
However, an inline box or element, such as a <span>, image <img> sits together with previous and next
inline elements. Common inline elements are Spans <span>, Images <img>, Anchors <a>.

6.2.3 Adding CSS Comments

When it’s time to edit a style sheet weeks, months, or even years after building it, you may find yourself
questioning, “Why did I create that style? What does it do?” When you’re developing a website, you must
keep records of what you did and why. Thankfully, you don’t require a pad of paper to do this. You can add
your notes directly into your style sheets applying CSS comments.

A CSS comment is simply a note enclosed within two sets of characters, /* and */. As with HTML
comments, CSS comments aren’t read or acted on by a web browser, but they do let you create useful alerts
to your style sheets.

Example:

/* A one-line comment*/

/*

This is multi-line

Comment

*/

CSS Reset:

Web browsers make use of their own built in styles to style various tags: Headings are big and bold; links are
blue, and so on. A CSS Reset is a set of styles that overwrite browser styles, causing the default styles as
consistent as possible along all browsers. Eric Meyer, an industry expert, has worked on strengthening this
system over several years, creating a small set of styles that make writing CSS extremely easy from the start.
We need to copy styles in https://meyerweb.com/eric/tools/css/reset/ and paste in the beginning of the
stylesheet.

6.2.4 CSS Code Formatting:

Code formatting has nothing in any way to do with how the CSS works. These are simply visual choices by
the coder. But that's not to say formatting isn't essential. It impacts how it feels to write CSS, how convenient
it is to read, how easy it is to navigate, and how easy it is to revisit and familiarize you with previously written
CSS. The reason there are so many options with CSS formatting is that there are no strict syntax rules when it
comes to spacing and line-breaks.

• Single-line Format: This is most likely the most space and size efficient, short of being totally
compressed to remove all spaces and line breaks. This approach would need the least vertical and
horizontal scrolling as you write and edit CSS, but at the probable cost of appearing untidy and
slightly complicated to read and find things you are searching for.

div.wrapper {margin:0 auto; padding:200px 0 0 0; width:1140px; z-index:2}


ul { position: absolute; top:0; left:430px; padding:120px 0 0 0; }
ul li { display: inline; margin:0 10px 0 0; }

• Multi-line Format: This is the most prevalent approach. It is the simplest to read, which is why
most of the designers use this format.

div.wrapper{
margin: 0 auto;
padding: 200px 0 0 0;
width:1140px;
z-index:2;
}

ul{

position: absolute;

top:0;

left:430px;

padding:120px 0 0 0;

ul li{

display: inline;

margin:0 10px 0 0;

}
6.2.5 Validate Your CSS Code:

It’s easy to produce a typo when crafting CSS and one little mistake can put all of your cautiously designed
designs out of whack. When your CSS infused web page doesn’t appear as you imagine, a basic CSS error may
be the reason. The W3C CSS validator is a good first stop when troubleshooting your designs.

Just as you ought to make sure you’ve properly written the HTML in your web pages applying the W3C
HTML validator, you should also verify your CSS code to ensure it’s clean. The W3C provides an online tool
for CSS checking as well: http://jigsaw.w3.org/css-validator. It works just like the HTML validator: You can
type the URL of a web page (or even just the address to an external CSS file), upload a CSS file or copy and
paste CSS code into a web form and submit it for validation.

6.2 Check Your Progress

Fill in the blank

1. 2 parts of CSS rule are: _______ and _________.

6.3 Summary

Cascading Style Sheets (CSS) is a simple language defining styles. It was first introduced in 1994. You can add
CSS to HTML file in 3 ways namely, Internal CSS, Inline CSS and External CSS. CSS syntax has 2 parts: a
selector and a declaration block. Many different units of measurements like px, rem, em, percentage etc can
be used in CSS.

6.4 Check Your Progress Answers

6.1

1. Cascading Style Sheets


2. Internal CSS, Inline CSS, External CSS

6.2

1. Selector, declaration block


Chapter 7

CSS: Selectors

7.0 Objectives

7.1 Introduction

7.1.1 Element Selector

7.1.2 ID Selector

7.1.3 Class Selector

7.1.4 Universal Selector

7.1.5 Descendant Selector

7.1.6 Child Selector

7.1.7 Sibling Selector

7.1.8 Attribute Selector

7.1.9 Grouping Elements

7.1.10 Pseudo Class

7.2 Inheritance

7.2.1 Specificity Calculator

7.2.2 !important

7.3 Summary

7.4 Check Your Progress Answers

7.0 Objectives

After studying this chapter you will be able to understand

- Meaning of css selector and different types of selectors

- Specificity in CSS

7.1 Introduction

CSS is a collection of rules, which are made up of two parts, selector and declaration. A selector is used to
select the element you want to apply styles to, and a declaration is the combination of a property and a value
for that element. Selecting the correct selector is the key to working effectively with CSS.
7.1.1 Element Selector:
An element selector is the name of an HTML element (tag). Element selector often called type or tag
selectors, are highly efficient styling tools, as they apply to every single incidence of the tag on a web page.

Example:

HTML

<p>Some Text Here</p>

CSS

p{

background-color: yellow;

7.1.2 Id Selector

An ID selector applies styles to elements which have the same id attribute in their opening HTML tag. Unlike
classes, which can be used to multiple elements in the same page, IDs must be unique within a page. It’s
alright to apply the same ID on different pages, provided that it’s used only once on each page. In CSS file
the selector is defined by prefixing the ID with the hash or pound sign (#).

Example:

HTML

<div id=”main”>Some Text here</div>

CSS

#main{

background-color: yellow;

7.1.3 Class Selector

When you'd like to give one or two images on a page a black thick border while leaving the majority of other
images unstyled, in such situation you can use a class selector.

Example:

HTML
<img src=”image01.jpg” class=”mybox”>

<img src=”image02.jpg” class=”mybox”>

<img src=”image03.jpg”>

CSS

.mybox{

border:10px solid #000;

7.1.4 Universal Selector

The universal selector is represented by an asterisk (*) and selects every element that makes up a web page

Example:

*{

font-size: 16px;

7.1.5 Descendant Selector

Descendant selectors are great for styling elements that exist inside of other elements. A descendant selector
matches any element that is a descendant of another. To create a descendant selector, separate the two
selectors by a space, putting the ancestor first.

Example:

HTML

<div id=”main”>

<p>Some Text Here</p>

</div>

CSS

#main p{

background-color :black;

The above code selects all <p> tags inside the element having id “main”

7.1.6 Child Selector


The child selector is used to select elements with a specific parent. It only selects immediate descendant of an
ancestor. This means that elements which are not directly a child of the specified parent element are not
selected. The child selector uses an additional symbol-an angle bracket (>) to show the relationship between
the two elements.

Example:

HTML

<section>

<div>

<p>First Paragraph</p>

</div>

<p>Second Paragraph </p>

</section>

CSS

Section > p {

background-color: yellow;

In the above CSS code, the second <p> gets selected as it is the only direct child of <section> element. The
first <p> tag inside <div> element is not a direct child of <section> tag hence won’t get selected.

7.1.7 Sibling Selector

Parent-child relationships aren’t the only ones in the HTML family tree. Sometimes you need to select a tag
based not on its parent tag but on its sibling tags that share a common parent. The sibling selector uses an
additional symbol-plus (+) to show the relationship between the two elements.

Following code selects every <p> elements that are placed immediately after <div> elements:

Example:

div + p{

background-color: yellow;

General Sibling Selector


The general sibling selector is used to select elements that is placed after (though not necessarily immediately)
the first specified element. It only selects element if both are children of the same parent. The general sibling
selector uses an additional symbol tilde (~) to indicate the relationship between the two elements.

Select and style every <p> elements that are placed after <div> elements:

Example:

div ~ p{

background:#ff0000;

7.1.8 Attribute Selector

Attribute selectors allow you to select elements by referring to their attributes, such as alt, title, src and so on.

Example:

HTML

<a href=”#” title=”mylink”>Link</a>

CSS

A[title=”mylink”] {

background-color: red;

7.1.9 Multiple / Group Selectors:

Occasionally you need an easy way to apply the same formatting to many different elements. To work with
selectors as a group, just create a list of selectors separated by commas. Thus, to style all the heading tags with
the same color, you can write following rule:

Example:

h1, h2, h3, h4, h5, h6{

color: red;

}
7.1.10 Pseudo Class

A pseudo-class doesn’t rely on a class attribute in the HTML markup, but is applied automatically by the
browser depending on the position of the element or its interactive state.

The syntax of pseudo-classes:

selector: pseudo-class{

property: value;

Link-related pseudo class selectors

: link - The :link CSS pseudo-class represents an element that has not yet been visited.

Example:

/* unvisited link */

a:link{

color:#FF0000;

:visited - Selects links that have already been visited by the current browser.

Example:

/* visited link */

a:visited{

color:##00FF00;

:hover - When the mouse cursor rolls over a link, that link is in its hover state and this will select it.

Example:

/* mouse over link */

a:hover{
color:##FF00FF;

:active - Selects the link while it is being activated

Example:

/* Seleted link */

a:active{

color:##0000FF;

:focus - The :focus CSS pseudo-class represents an element (such as a form input) that has received focus.

input: focus{

width:250px;

:first-child - The :first-child CSS pseudo-class represents the first element among a group of sibling elements.

In the following example, the selector matches any <p> element that is the first child of any element:

Example:

p:first-child{

color: green;

:last-child - The :last-child CSS pseudo-class represents the last element among a group of sibling elements.
Specify a background color for the <p> element that is the last child of its parent:

Example:

p:last-child{

background-color: #ff0000;
}

:first-of-type

The :first-of-type CSS pseudo-class represents the first element of its type among a group of sibling elements.

Selects any <p> that is the first element of its type among its siblings

Example:

p:first-of-child{

color: red;

:last-of-type
The :last-of-type CSS pseudo-class represents the last element of its type among a group of sibling elements.

Selects any <p> that is the last element of its type among its siblings

Example:

p:last-of-child{

color: yellow;

7.1 Check Your Progress

True or False

1. An element selector is the name of an HTML element (tag).


2. ID selector applies styles to elements which have the same id
3. Universal selector selects only one element
4. ">" is used for sibling selector

7.2 Inheritance

Inheritance is the process by which some CSS properties applied to one tag are passed on to nested tags. For
example, a <p> tag is always nested inside of the <body> tag, so the properties applied to the <body> tag
get inherited by the <p> tag. In the following example because of the inheritance rule, text inside <p> will be
displayed in green color.
HTML

<body>

<p>Some nice text here</p>

</body>

CSS

body { color: green; }

7.2.1 Specificity Calculator

Specificity is the means by which browsers decide which CSS property values are the most relevant to an
element and, therefore, will be applied.

Specificity is a weight that is applied to a given CSS declaration, determined by the number of each selector
type in the matching selector. When multiple declarations have equal specificity, the last declaration found in
the CSS is applied to the element. Specificity only applies when the same element is targeted by multiple
declarations. As per CSS rules, directly targeted elements will always take precedence over rules which an
element inherits from its ancestor.

Selectors Inline Style Id Class Element


Points 1000 100 10 1
Example <style="color:red"> #test .entry-content div span{ }
</style>

Example:

HTML

<div id=”test” class=”enter-content”>

<span>Text</span>

</div>

CSS

#test span { color: green; }

div span { color: black; }

.enter-content span { color : blue; }

span { color: red; }


No matter what the order, the text will be green because the rule #test span{color:green;} is the most
specific. The id selector #test span (100 points) is more specific than the element .entry-content span (10
points), div span and span (1 point each).

7.2.2 !important

When “!important” rule is used on a style declaration, this declaration overrides all other declarations. We can
use the “!important” rule to override the specificity rule we learned in the above example.

Example:

CSS

#test span { color: green; }

div span { color : black; }

span { color : red! important; }

In continuation with the previous example, we have added “!important” rule to the span { color: red }. As the
“!important” rule overrides specificity rule, here the text will be of color red.

7.2 Check Your Progress

True or False

1. Inline style has highest specificity points

7.3 Summary

Cascading Style Sheets (CSS) is a simple language defining styles. It was first introduced in 1994. You can add
CSS to HTML file in 3 ways namely, Internal CSS, Inline CSS and External CSS. CSS syntax has 2 parts: a
selector and a declaration block. Many different units of measurements like px, rem, em, percentage etc can
be used in CSS.

7.4 Check Your Progress Answers

7.1

1. True
2. True
3. False
4. False

7.2

1. True
Chapter 8

Formatting Text

8.0 Objectives

8.1 Introduction

8.1.1 Font Family

8.1.2 Using Web Safe Fonts

8.1.3 Using External Fonts

8.1.4 Using Google Fonts

8.2 CSS properties for text management

8.2.1 Adding Colors to Text

8.2.2 Changing Font Size

8.2.3 Font Weight

8.2.4 Font Style

8.2.5 Text Transformation

8.2.6 Text Decoration

8.2.7 Text Alignment

8.2.8 Font Variant

8.2.9 Letter Spacing

8.2.10 Word Spacing

8.2.11 Line Height

8.2.12 Text Indent

8.2.13 Word Wrapping

8.3 Styling List Elements

8.3.1 List Style Type

8.3.2 List Style Position

8.3.3 List Style Image

8.3.4 List Style


8.4 Summary

8.5 Check Your Progress Answers

8.0 Objectives

After studying this chapter you will be able to understand

- how to set font family

- how to use web safe and external fonts

- how to use many CSS properties for text management

8.1 Introduction

Attractive and readable text is essential to the success of a website. CSS has a significant number of properties
specific to formatting text, providing you control not only over fonts and colors, but also allowing you to
change the distance between lines, words, and individual letters.

8.1.1 Font Family

The primary thing you can do to make text on your website appear even more interesting is to use different
fonts to headlines, paragraphs, and other written elements on your pages. To apply a font to a CSS style, you
use the font-family property and state the font you wish to use.

p{

font-family : ”Times New Roman”,Times,serif”;

Note: If the name of a font family is more than one word long, it must be in quotation marks, like: "Times
New Roman".

The font-family CSS property specifies a prioritized list of one or more font family names and/or generic
family names for the specified element. The font-family property should have several font names as a
"fallback" system. If the browser does not support the first font, it tries the next font, and so on.

Generic family Font family Description


Serif Times New Roman, Serif fonts have small lines at the end of the
Georgia characters
Sans-serif Arial, Verdana "Sans" means without - these fonts do not have
the lines at the end of the characters
Cursive Viner Hand ITC Cursive fonts look handwritten or done with a
calligraphic pen.
Monospace Courier New, Lucida All monospace characters have the same width
Console

8.1.2 Using Web Safe Fonts:

In the past, the font-family property only functioned if your site’s visitors had the same font installed on their
computers. Quite simply, if someone browsing your site didn’t have the font you applied in the website, on
his computer, the content would display with the web browser’s default font like Times New Roman. Web
safe fonts are those fonts that are most likely to be installed on the most of the devices accessing the web.
Between computers with different operating systems, you can locate around 50 web safe fonts, but with
mobile devices now accessing the web too, the number of web safe fonts drops to just a few. Arial, Times
New Roman, Times, Courier New, Courier, Verdana, Georgia, Garamond, Trebuchet MS and Impact are
some of the Web safe fonts.

8.1.3 Using External Fonts:

For several years, web designers, annoyed by the limited range of web-safe fonts, have been asking for the
power to embed different fonts in their web pages. The condition began to transform quickly after 2008-
2009, when all major browsers finally provided support for CSS @font-face rules that specified the location
of font files. This caused the creation of many new fonts designed specifically for embedding in web pages.
Google font (https://fonts.google.com) is the most popular place to download free fonts. Some of the other
popular sites are Da Font (https://www.dafont.com) and Font Squirrel (https://www.fontsquirrel.com).

Fonts come in the following file formats:

• .ttf and .otf : These are the font formats most commonly used for computer fonts.

• .eot : Embedded Open Type fonts work only in Internet Explorer.

• .woff : Web Open Font Format files is a newer font format that’s designed specifically for the Web.

• .svg : Scalable Vector Graphic format isn’t a font format, per se. It’s actually a way to create vector graphics.

Basic syntax for adding external font looks like:

@font-face{

font-family:my-font-name;
src: url(format);

The font-family property defines the name of the web font. You can select any name you want. If it has
spaces, the name must be surrounded in quotes. The src property instructs the web browser where to find the
font files. Provide multiple values for several font formats as a comma-separated list.

There are two ways to use the external fonts:

1. Upload font file to the server: First upload all font files to web server. Then in CSS file add
following:

@font-face{
font-face : ‘ My Font Name ’;
src : url ( ‘myfontname.eot’ );
src : url ( ‘myfontname.eot’?#iefix’ ) format(‘embedded-opentype’),
url ( ‘myfontname.woff’ ) format(‘woff’),
url ( ‘myfontname.ttf’ ) format(‘truetype’),
url ( ‘myfontname.svg’ ) format(‘svg’);
}

2. Link to the font file on CDN (Content Delivery Network)

Inside HTML File Link “Roboto” font hosted on Google CDN as below
<link href=”http://font.googleapis.com/css?family=Roboto” rel=”stylesheet”>

Then use the font in CSS file as below


body{
font-family : ‘Roboto’, sans-sarif;
}

Note: Many fonts are protected by copyright, so you can’t upload font files to your website without first
examining the license and seeing if there are any limitations on its use. Even if you have paid for a font, you
cannot presume that you have the right to use it in a website. It might be limited to use on your local
computer. That being said, there are hundreds of fonts that you can use, and many of them are available free
of charge.

8.1 Check Your Progress

True or False

1. .ttf and .otf are the font formats most commonly used for computer fonts
8.2.1 Adding Colors to Text

Coloring your text with CSS is easy. You have many different ways to specify the exact color you want, but
they all follow the common basic structure.

• Hexadecimal Color Notation: In this example, the color value is a hexadecimal number producing
an orange color. The most well-known color system applied by web designers is hexadecimal
notation. A color value-like #FFA500 - in fact has three hexadecimal numbers - in this example FF,
A5, 00 - each of which specify an amount of red, green, and blue, correspondingly.

color: #FFA500;

• RGB: You can even use the RGB - red, green, blue-method, this is popular in computer graphics
programs. The color value is made up of three numbers representing numbers between 0-255 for
each hue (red, green, and blue).

color: rgb (255,165,0);

• RGBA: To add depth to a page, consider one of the more recent color methods. RGBA is short for
Red, Green, Blue, Alpha, and it functions just like the RGB colors with the addition of an alpha
channel. That is, you can state a level of opacity (transparency) so that the color isn’t solid, but see-
through. To the RGB colors, you add one last number, a value between 0 and 1. A value of 0 makes
the color transparent, while 1 makes the color totally opaque.

color: rgba(255,165,0,0.5);

8.2.2 Changing Font Size

Varying the size of text on a web page is a nice way to create aesthetic interest and direct your visitor's focus
to important aspects of a page. Headlines in large type sizes catch attention, whereas copyright notices shown
in small type quietly recede from importance. The font-size property sets text size. It’s always followed by a
unit of measurement (px, em, rem), like so:

Example:

h1{

font-size: 40px;

p{

font-size: 16px;

}
Other methods you can use to change the font size:

Keywords: Font-size can be changed using a series of keywords: xx-small, x-small, small, medium, large, x-
large, and xx-large.

font-size: large;

Percentages: When you use a percentage value, the font size is relative to the parent element’s font size,
which is inherited. Suppose the inherited font-size of an element is 16px, and if you declare that element’s
font-size as 50%, then the measured font-size is 8px.

font-size: 50px;

8.2.3 Font Weight

The font-weight property lets you make text bold, normal or light. The font-weight property accepts the
following values: bold, bolder, lighter, normal and one of nine values increasing in steps of 100 from 100 to
900 (300 equals light, 400 equals normal, and 700 equals bold).

Example:

p{

font-weight: bold;

8.2.4 Font Style

By using the font-style property, you can change the style of a font between normal, italic, and oblique.

p{

font-style: italic;

8.2.5 Text Transformation

With text-transform, you can make text all uppercase, all lowercase, or even capitalize the first letter of each
word. Text Transform accepts these values: none, uppercase, lowercase, and capitalize.
Example:

p{

text-transform: uppercase;

8.2.6 Text Decoration

CSS also provides the text-decoration property to add several improvements to text. Make use of the text
decoration property by applying one or more of the following keywords: underline, overline, line-through, or
blink.

Example:

a{

text-decoration: none;

8.2.7 Text Alignment

Applying the text-align property, you can center a paragraph on a page, align the text along its left or right
edge, or justify both left and right edges. Mostly, text on a page is left aligned, but you may choose to center
headline. Languages that read from right to left, like Hebrew and Arabic, need right-alignment. To alter the
alignment of text, make use of any of the following values left, right, justify, center:

Example:

h1{

text-align: center;

8.2.8 Font Variant

For more typographic elegance, you can also switch to the font-variant property, which allows you set type as
small-caps. In small cap style, lowercase letters turn up as somewhat downsized capital letters. Although hard
to read for long stretches of text, small caps give your page an old-world, bookish look when applied on
headlines and captions. To create small-cap text:
Example:

p.small{

font-variant: small-caps;

8.2.9 Letter Spacing

The letter-spacing property manages the amount of horizontal space between letters. In print terminology,
this is referred to as tracking. You can use normal, or px, em, rem as unit with number. Negative number
decreases the space between letters.

Example:

h1{

letter-spacing: normal;

h2{

letter-spacing: 2px;

h3{

letter-spacing: -1px;

8.2.10 Word Spacing

Similar to letter-spacing, the word-spacing property helps you alter the spacing between words. The primary
value of “normal” indicates the default space between words, and you can define a length value to alter this
space as you want.

Example:

p.small{

word-spacing: -1px;

}
8.2.11 Line Height

The line-height property handles the vertical space or leading between lines of the text. Setting the line-height
property impacts the readability of a web page. Not enough space and the text look cramped and very
difficult to read. A lot of space and the reader’s eyes wander, making reading equally challenging.

This property takes a length, percentage, or number as value. A number value is a multiplication of an
element’s font size. There’s no unit (like em, rem or px) after this value. You can also use the keyword normal
to reset line-height to its default value. Negative values are not allowed.

Example:

p.a{

line-height: normal;

p.b{

line-height: 1.6;

p.c{

line-height: 80%;

8.2.12 Text Indent

The text-indent property accepts length or percentage, and indents the first line of text in every block by the
length selected. In cases where the value is a percentage, the indentation is a percentage of the parent
element’s width.

Example:

p{

text-indent: 50px;

}
8.2.13 Word Wrapping

Whenever there are no spaces in text, for example, with a long URL, the browser is unable to break it,
causing an ugly overflow. All latest browsers support the word-wrap property to manage this problem. It
takes normal, and break-word values:

Example:

p{

word-wrap: break-word;

8.2 Check Your Progress

True or False

1. You can add color to the text with text-color property


2. The font-weight property lets you make text bold
3. You can add underline to the text with text-decoration property

8.3 Styling List Elements

The CSS list properties allow you to set different list item markers for ordered lists and unordered lists. You
can set an image as the list item marker as well.

8.3.1 List Style Type

List Style Type property accepts disc (a solid round bullet), circle (a hollow round bullet), or square (a solid
square) values.

Example:

ul .a{

list-style-type: circle;

ul .b{

list-style-type:squre;

}
ul .c{

list-style-type:disc;

8.3.2 List Style Position

You can control the position of the bullet points applying the list-style-position property. You can either have
the bullet appear outside of the text (the way browsers normally display bullets) or inside the text block itself.

Example:

ul .a{

list-style-position: outside;

ul .b{

list-style-position: inside;

8.3.3 List Style Image

The CSS list-style-image property lets you define a path to a graphic file on your server, just like you specify a
file when adding an image to a page by applying the src attribute of the HTML <img> tag. You can use the
property like this:

Example:

ul {

list-style-image: url (‘image.gif’);

8.3.4 List Style

The list-style shorthand property takes the same values as the individual list-style-type, list-style position, and
list-style-image properties. You can define all three values, separated by a space, or just one or two.

Example:
ul {

list-style: squre inside url(“image.gif”);

8.3 Check Your Progress

True or False

1. You can control the position of the bullet points applying the list-style-position property

8.4 Summary

With font-family property you can set font. Other important properties for font mangement are font-size,
font-weight, font-style etc. You can set text color with color property. Line height, text indent, word
wrapping are some of the paragraph styles.

8.5 Check Your Progress Answers

8.1

1. True

8.2

1. False
2. True
3. True

8.3

1. True
Chapter 9

Understanding Box Model

9.0 Objectives

9.1 Introduction

9.1.1 Width and Height

9.1.2 Margins and Padding

9.1.3 Adding Borders

9.1.4 Creating Rounded Corners

9.2 Background

9.2.1 Background Color

9.2.2 Background Image

9.2.3 Background Repeat

9.2.4 Background Position

9.2.5 Background Size

9.2.6 Background Shorthand Property

9.3 Summary

9.4 Check Your Progress Answers

9.0 Objectives

After studying this chapter you will be able to understand

- concept of box model

- properties like padding, margin, border and border –radius.

9.1 Introduction

You already know that all elements on a web page are treated as boxes-some are block-level, some are inline-
level. The CSS box model is mainly a box that wraps around every HTML element. It includes: margins,
borders, padding, and the actual content. The image below illustrates the box model:
Explanation of the different parts:

• Content - The content of the box, where text and images appear, it has width and height.
• Padding - Horizontal and vertical space surrounding the content
• Border - A border that goes around the padding and content
• Margin - Horizontal and vertical space outside the border

Browsers make use of default values to individual elements. Such as, paragraphs have default top and
bottom margins, but no padding or border, whereas <div> elements have no padding, border, or
margins. You can use CSS to adjust the padding, border, and margins individually on each side of an
element to control its look and layout.

9.1.1 Width and Height

The width and height properties set the horizontal and vertical sizes of an element. The default value of
both properties is auto, meaning that the element expands or contracts to fit the natural size of the
content.

Using these properties to a style is very easy. Just type the property followed by any of the CSS
measurement units like px, em, rem or percentage (%) you’ve already learned.

Example:
div{

width:300px;

height:200px;

}
span{

width:30%;

height:25%;

There are four additional properties that let you to restrict the dimensions of an element within a given range,
namely minimum width (min-width), maximum width (max-width), minimum height (min-height) and
maximum height (max-height). Any unit of measurements like px, em, rem or percentage (%) can be used for
these properties.

Minimum Width:

The min-width property is used to set the minimum width of an element.

Example:

div{

min-width: 300px;

height:100px;

background-color :blue;

Maximum Width:

The max-width property is used to set the maximum width of an element.

Example:
div{

max-width: 500px;

height: 100px;

background-color: red;

Minimum Height:

The min-height property is used to set the minimum height of an element.

Example:
div{

width: 100px;

min-height: 100px;

background-color: blue;

Minimum Height:

The max-height property is used to set the maximum height of an element.

Example:
div{

width: 100px;

max-height: 700px;

background-color: blue;

9.1.2 Margins and Padding

Padding:

Both padding and margins create vertical and horizontal space around elements. But, the important difference
is that padding goes inside the border and margin goes outside the border. You can use unit of measurements
px, em, rem or percentage (%). But, negative values are not allowed.

Padding Top:

The padding-top CSS property sets the height of the padding area on the top of an element.

Example:
padding-top:20px;

Padding Right:

The padding-right CSS property sets the width of the padding area on the right side of an element.

Example:
padding-right : 5em;
Padding Bottom:

The padding-bottom CSS property sets the height of the padding area on the bottom of an element.

Example:
padding-bottom :10%;

Padding Left:

The padding-left CSS property sets the width of the padding area on the left side of an element.

Example:
padding-left :10px;

Padding Shorthand Property:

The padding CSS property creates the padding area on all four sides of an element. It is shorthand for setting
all individual padding at once: padding-top, padding-right, padding-bottom, and padding-left.

Example:

padding :10px;

The padding property may be specified using one, two, three, or four values.

• When one value is specified, it applies the same padding to all four sides.

/* Apply to all four sides */

padding: 30px;

• When two values are specified, the first padding applies to the top and bottom, the second to the left and
right.

/* vertical | horizontal */

padding: 5% 10%;

• When three values are specified, the first padding applies to the top, the second to the left and right, the
third to the bottom.

/* top | horizontal | bottom */

padding: 10px 20px 20px;


• When four values are specified, the padding apply to the top, right, bottom, and left in that order
(clockwise).

/* top| right | bottom | left */

padding: 5px 10px 0 20px;

Margin:

Implementing margin is a great way of creating space between two elements on a web page. Using margins is
very similar to padding. There are separate properties to control the margin independently on each side of an
element, as well as a shorthand property.

Margin Top:

The margin-top CSS property sets the margin area on the top of an element. A positive value will place it
further than normal from its neighbors, while a negative value will place it closer.

Example:

margin-top: 15px;

Margin Right:

The margin-right CSS property sets the margin area on the right side of an element. A positive value will
place it further than normal from its neighbors, while a negative value will place it closer.

Example:

margin-right: 25px;

Margin Bottom:

The margin-bottom CSS property sets the margin area on the bottom of an element. A positive value will
place it further than normal from its neighbors, while a negative value will place it closer.

Example:

margin-bottom: 15px;

Margin Left:

The margin-left CSS property sets the margin area on the left side of an element. A positive value will place it
further than normal from its neighbors, while a negative value will place it closer.
Example:

margin-left: 20px;

9.1.3 Border:

The CSS border properties let you specify the style, width, and color of an element's border.

Border Style

The border-style property specifies what kind of border to display.

The following values are allowed:

• dotted - Defines a dotted border


• dashed - Defines a dashed border
• solid - Defines a solid border
• double - Defines a double border
• none - Defines no border
• hidden - Defines a hidden border

Example:

p.dotted{ border-style : dotted; }

p.dashed{ border-style : dashed; }

p.solid{ border-style : solid; }

p.double{ border-style : double; }

p.none{ border-style : none; }

Border Width

The border-width property specifies the width of the four borders.

The width can be set as a specific size (px, em, rem etc) or by using one of the three pre-defined values: thin,
medium, or thick.

Example:

p.one{

border-style: solid;

border-width: 5px;

}
p.two{

border-style: solid;

border-width: medium;

p.three{

border-style: solid;

/* top| right| bottom | left*/

border-width: 2px 10px 4px 20px;

Border Color

The border-color property is used to specify the color of the four borders.

The color can be set by:

• name - specify a color name, like "red"


• Hex - specify a hex value, like "#ff0000"
• RGB - specify a RGB value, like "rgb(255,0,0)"
• transparent

Example:
p.one{

border-style: solid;

border-width: 3px;

border-color: red;

p.two{

border-style: solid;

border-width: 3px;

border-color: #009900;

}
p.three{

border-style: solid;

border-width: 3px;

border-color: rgb(0,0,204);

Border - Shorthand Property

To shorten the code, it is also possible to specify all the individual border properties in one property.

The border property is a shorthand property for the following individual border properties:

• border-width
• border-style (required)
• border-color

Example:
p{

border: 5px solid red;

You can also specify all the individual border properties for just one side:

Example:
p{

border-top: 6px solid blue;

border-right: 6px solid yellow;

border-bottom: 6px solid red;

border-left: 6px solid black;

}
Rounded Borders

The border-radius property is used to add rounded borders to an element:

Example:
p{

border: 2px solid red;

border-radius:5px;

9.1 Check Your Progress

True or False

1. A border goes inside the padding.


2. Margin is the horizontal and vertical space outside the border.
3. The border-radius property is used to add rounded borders.

9.2 Background

The key to the good web design is attracting the visitor’s eyes to important parts of the page. Background
colors and images make it easier to break up the page and focus attention.

9.2.1 Background Color

The background-color CSS property sets the background color of an element.

Example:
body{ background-color: red;}

h1{ background-color: rgb(0, 0, 255);}

p{ background-color:#ff0000;}

9.2.2 Background Image

The background-image CSS property sets one or more background images on an element.

Example:
body{

background-image: url(“image.png”);

}
div{

background-image: url(“assets/images/image.png”);

9.2.3 Background Repeat

The background-repeat CSS property specifies how background images are repeated. A background image
can be repeated on the horizontal axis, the vertical axis, both axes, or not repeated at all. The values we can
use for background -repeat property are repeat, repeat-x, repeat-y, no-repeat.

Example:

body{

background-image: url(“image.png”);

/* repeat vertically */

background-repeat: repeat-y;

9.2.4 Background Position

The background-position CSS property sets the initial position for each defined background image.

The first value is horizontal position (x axis) while the second value is vertical position (y Axis).

Example:

body{

background-image: url(‘image.png’);

background-repeat: no-repeat;

background-position: left-top;

div{

background-image: url(‘picture.png’);

background-repeat: no-repeat;

background-position: 50% 0;

}
The value for background-position may be:

1. One of the keyword values top, left, bottom, right. This specifies an edge against which to place the
item.
2. We can use a length like bottom 100px or percentage value like 50% .

9.2.5 Background Size

The background-size CSS property specifies the size of an element's background image. The image can be left
to its natural size, stretched to a new size, or constrained to fit the available space while preserving its intrinsic
proportions.

Example:

.first{

background-image: url(‘image.png’);

background-repeat: no-repeat;

background-size: auto;

.second{

background-image: url(‘image.png’);

background-repeat: no-repeat;

background-size: 300px 100px;

.third{

background-image: url(‘image.png’);

background-repeat: no-repeat;

background-size: cover;

}
The values we can use for background-size are

• Auto: The default value. The background image is displayed in its original size
• Contain: Resizes the image as large as possible without cropping or stretching the image.
• Cover: Scales the image as large as possible without stretching the image. If the proportions of the
image differ from the element, it is cropped either vertically or horizontally so that no empty space
remains.
• Length: Stretches the image in the corresponding dimension to the specified length. (e.g. 300px)
• Percentage: Stretches the image in the corresponding dimension to the specified percentage. (e.g.
50%)

9.2.6 Background Shorthand Property

The background CSS property allows you to adjust all background style options at once, including color,
image, origin and size, repeat method, and other features. The property is a shorthand that sets the following
properties in a single declaration: background-color, background-image, background-position, background-
repeat and background-size.

Example:

body{

background: blue url(“image.jpg”) no-repeat fixed center;

9.2 Check Your Progress

True or False

1. The background-size CSS property specifies how background images are repeated

9.3 Summary

Every HTML box element is composed of four parts, defined by their respective edges: the content, padding,
border and margin. The content part of element has width and height. You can use properties like padding,
border and margin to manage the space around the content. You can change background color or image with
background property.

9.4 Check Your Progress Answers

9.1
1. False
2. True
3. True

9.2

1. False
Chapter 10

Page Layout

10.0 Objectives

10.1 Introduction

10.2.1 Top, Right, Bottom, Left

10.2.2 Applying Floats to Your Design

10.2.3 Clearing Float

10.3 Display Property

10.3.1 Controlling Visibility

10.3.2 Z-index

10.3.3 Controlling Overflow

10.3.4 Working with Flexbox

10.4 Summary

10.5 Check Your Progress Answers

10.0 Objectives

After studying this chapter you will be able to understand

- use position property

- how to float elements

- control visibility

10.1 Introduction

Positioning enables you to take elements out of the regular document layout flow, and make them act in a
different way, for example sitting on top of one another, or always remaining in the same place inside the
browser viewport. By default, HTML elements are all position: static, this means they are positioned
according to their actual place in the default flow. Statically positioned elements cannot have their top, left,
right, and bottom properties altered.

There are a number of different types of positioning that you can put into effect on HTML elements. To
make a particular type of positioning active on an element, you can use the position property.
Static: Static positioning is the default that each and every element gets. This leaves the element in the
normal document flow. The only time you need to use static is if you want to override another style rule to
make an element act like normal HTML.

Example:

p{

position: static;

background: yellow;

Relative: This moves the element relative to its normal position in the document flow, but without impacting
the position of other elements. By indicating position: relative on an element, you tell the browser to position
it relative to its default position in the document flow. You can now make use of left, top, right, or bottom
rules to the element and it will move out of its location as you specify.

Example:

p{

position: relative;

Absolute: This takes out the element, including any child elements, entirely from the flow of the document,
and positions it at the chosen offsets. If the element is nested inside another positioned element, the offsets
are calculated with reference to the positioned parent. Usually, the offsets are calculated with reference to the
page.

Example:

p{

position: absolute;

background: blue;

}
Fixed: This works simply the same way as absolute positioning, with one key difference - unlike absolute
positioning fixes an element in place relative to the <html> element or its nearest positioned ancestor, fixed
positioning fixes an element in place relative to the browser viewport itself.

Example:

p{

position: fixed;

10.2.1 Top, Right, Bottom, Left:

You can specify where an element is positioned by setting offsets from its containing block with the top,
right, bottom, and left properties, all of which accept a length or a percentage.

Example:

div{

top:200px;

left:100px;

10.2.2 Applying Floats to Your Design:

Float-based layouts take benefit of the float property to position elements side-by-side and create columns on
a web page. The float property moves a page element to one side of the page. Any HTML element that
appears below the floated element moves up on the page and wraps around the float. The float property takes
one of three different values-left, right, and none. You should always give your floated element a width. To
move an image to the right side of the page as shown below:

Example:

img{

float: right;

width:300px;

10.2.3 Clearing Float:

Floats are effective design tools as they let content flow around them. Floating a photo lets text below it
move up and wrap around the image. When you’re creating float-based column designs, though, occasionally
you don’t want the content to move up and next to a floated element. In such situations you can use the clear
property. This property stops an element from wrapping around floats. You can use left, right and both as
value for clear property.

Example:

img{

clear: both;

10.2 Check Your Progress

True or False

1. Statically positioned elements cannot have their top, left, right, and bottom properties altered
2. clear property stops an element from wrapping around floats

10.3 Display Property:

CSS manages all elements as boxes, the two main types being block level and inline. The display property
provides you the power to change an element’s box type by using one of the values: block, inline, inline-
block, flex, none.

Example:

li{

display: inline-block;

10.3.1 Controlling Visibility:

The visibility CSS property can show or hide an element without impacting the layout of a document.
Visibility property accepts visible and hidden as values. The value visibility: hidden, hides the element but
does not remove it from the page layout. If you want to remove the element totally then you should use
display: none

Example:

span{

visibility: hidden;

}
10.3.2 Z-index:

The z-index CSS property identifies the z-order of a positioned element and its descendants. When elements
overlap, z-order decides which one appears on the top of the other. An element with a larger z-index shows
up on the top of the other element with a lower z-index.

Example:

p{

z-index:100;

10.3.3 Controlling Overflow:

The overflow CSS property specifies what to do when an element's content is too big to fit in its block
formatting context. The overflow property takes visible, hidden, scroll, auto values. It is shorthand for the
overflow-x and overflow-y properties.

Example:

div{

overflow: hidden;

10.3.4 Working with Flexbox:

The main feature of flexible box layout is that it makes a block known as a flex container, in which the flow
of the document can be virtually turned on its head. Everything inside the flex container becomes a flex item
that can be displayed in a different order from the underlying HTML.

Following defines a flex container:

Example:

HTML

<div class=”container”>

<div>1</div>

<div>2</div>

<div>3</div>

</div>

CSS
.container{

display: flex;

The element inside flex container becomes flex items.

Flex Direction:

The flex-direction property defines in which direction the container wants to stack the flex items. flex-
direction property takes column, row, column-reverse, row-reverse as values.

Example:

.container{

display: flex;

flex-direction: column;

Flex Wrap:

The flex-wrap property specifies whether the flex items should wrap or not. The values you can use are wrap
and nowrap.

Example:

.container{

display: flex;

flex-direction: column;

flex-wrap: wrap;

Justify Content:

The justify-content property is used to horizontally align the flex items. Values accepted by this property are
center, flex-start, flex-end, space-around and space-between.

Example:

.container{

display: flex;

justify-content: center;
}

Align Items:

The align-items property is used to align the flex items vertically. The values accepted by this property are flex-
start, flex-end, center

Example:

.container{

display: flex;

height:200px;

align-items: center;

Check Your Progress

True or False

1. When elements overlap, z-order decides which one appears on the top of the other
2. Visibility property removes element from the page layout

10.4 Summary

With the help of position property, you can take elements out of the regular document layout flow. You can
use float property to position elements side-by-side. Visibility property hides the element but does not
remove it from the page layout. Flexbox is a new and exciting addition to CSS3, with concepts like flex
container, flex item, flex direction.

10.5 Check Your Progress Answers

10.2

1. True
2. True

10.3

3. True
4. False
Chapter 11

Responsive CSS

11.0 Objectives

11.1 Introduction

11.1.1 Different Screens and Screen Sizes

11.1.2 Media Queries

11.2 Summary

11.3 Check Your Progress Answers

11.0 Objectives

After studying this chapter you will be able to understand

- what is responsive design

- different devices used and their screen sizes

- how to use media queries to target different screen sizes

11.1 Introduction

It’s very difficult to read a four-column web page on a phone whose screen is just 320 pixels wide. It’s just as
difficult to read a single column of text that’s displayed across the 2560 pixels of a large desktop monitor.
Responsive web design, a term coined by web design pioneer Ethan Marcotte, is an effort to solve that
problem. Responsive web design, or RWD for short, enables you to change the complete layout of a page
based on browser window width, so you can develop the most readable presentation for each device, without
having to create multiple versions of the same website. RWD is not a single technology or technique. Rather,
it brings together several CSS and HTML methods to create web pages whose layouts adapt to different
screens.

Responsive web design technique takes advantage of several distinct tricks to make a page change its layout
based on the width of the browser screen. On a smartphone, for example, you can lay out a page in a single,
easy-to-read column to fit the narrow width of the screen while maintaining a multicolumn layout on wider
monitors.

RWD combines three main ideas: flexible grids for layout, flexible media for images and video, and most
importantly CSS media queries to create different styles for different screen widths.

• With flexible grids, you skip fixed-width layouts. Since smartphone screens come in a wide variety of
widths, it makes no sense to create a page at a fixed width; instead, you want the page to grow or
shrink to fit the particular device.
• Creating flexible media lets your images and videos scale to fit the appropriate screen real estate…big
photos for big monitors, smaller photos for small screens, and so on.
• Finally, media queries are a CSS technology that lets you send different styles to a browser based on
current conditions. For example, you can send one set of styles when the screen is less than 480
pixels wide and another set when the window is more than 760 pixels wide.

Simply add the following code to the <head> section of your web page

<meta name=”viewport” content=”width=device-width, initial-scale=1.0”>

The viewport refers to the browser screen, and the content attribute sets the width of the browser to the
width of the phone’s. In other words, on mobile browsers that tend to zoom out, you’re telling them not to
zoom out, but to just make the screen’s width match the actual display of the phone.

11.1.1 Different Screens and Screen Sizes

There’s a wide variety of widths for these devices. You can have small phones, large phones, tablets, laptops
and large screen pc. Here are screen width sizes of some of the current popular devices:

Small Screen Mobile Width Between: 320px - 576px

Smart Phone Width Between: 576px - 768px

Tablet Width Between: 768px - 1024px

Laptop Width Between: 1024px - 1920px

PC Width Between: 1200px - 2560px

Desktop First or Mobile First?


Another thing to consider is which device are you designing for first? You don’t need to create three separate
sets of styles, one for each width device you’re targeting. You can, and should, start with a default design; that
is, a design that works without media queries. You can then create media query styles to override the default
styles and reformat the page for the particular screen width. There are two main approaches:

• Desktop first. You can design your site with the desktop in mind. This becomes your base design,
and you can put all of these styles into an external style sheet and link it to the pages of your site as
you normally would.
• Mobile first. You can flip that approach on its head by designing first for mobile browsers. This
time, you put the basic small-screen styles in a regular external style sheet, and then refine the design
for tablets and desktops by adding columns and other adjustments for larger screens in media
queries.

11.1.2 Media Queries


CSS3 contains a method called media queries, that let you assign styles to a page based on the destination
browser’s width and height. Because of this method, you can build custom styles for mobile phones, tablets,
and desktop browsers, and, in turn, customize your site’s presentation so it looks its best on each type of
device.
The main purpose of responsive design is to give your site’s visitors the most readable and attractive
presentation possible. This generally means customizing the design to look its best at different browser
widths. Many designers think of three target screens related to the three most common web browsing
devices: smartphones, tablets, and desktop computers. A media query is just a question asked to the web
browser: “Is your screen less than 576 pixels wide?” If the answer is Yes, then the browser launches a style
for just that size device as shown below.

Example:

@media(max-width:576px){

body{

/* style properties go here */

You can also use min-width instead of max-width as below:

@media(min-width: 768px){

body{

/* style properties go here */

Similarly you can target both min-width and max-width together.

@media(min-width: 576px) and (max-width: 768px) {

body{

/* style properties go here */

}
11.1 Check Your Progress

True or False

1. CSS media queries create different styles for different screen widths
2. Flexible media lets your images and videos scale to fit the appropriate screen size.
3. In desktop first approach you can design your site with the mobile in mind

11.2 Summary

Responsive web design technique use many distinct tricks to make a page change its layout based on the
width of the browser screen. You can either build RWD based site with Desktop First approach or Mobile
first approach.

11.3 Check Your Progress Answers

11.1

1. True
2. True
3. False

By Hugo Giraudel and Miriam Suzanne


Chapter 12

Advanced CSS and Animation

12.0 Objectives

12.1 Introduction

12.2 Advanced CSS

12.2.1 Text Shadow

12.2.2 Box Shadow

12.2.3 Gradient

12.2.4 Transformations

12.2.5 Transitions

12.3 Summary

12.4 Check Your Progress Answers

12.0 Objectives

After studying this chapter you will be able to understand

- how to add shadow effect to text and box

- add gradient background color

- how to add transition and transformation effects

12.1 Introduction
CSS continues to mature as a language, and as it does it gives us a greater ability to create with code. Box
shadows, gradient effects, transforms, transitions, and CSS animations are excellent examples of things we
can create with CSS.

12.2.1 Text Shadow


The text-shadow CSS property adds shadows to the text. It takes a comma-separated list of shadows to be
used to the text. The text-shadow property needs four pieces of information: the horizontal offset (how far to
the left or right of the text the shadow should appear), the vertical offset (how far above or below the text the
shadow should appear), the blurriness of the shadow, and the color of the drop shadow.

Example:

Text-shadow: 4px 4px 8px #00000;


Multiple Text Shadows

To add more than one shadow to the text, we need to add a comma-separated list of shadows.

Example:

Text-shadow: - 4px -6px 8px #333333, 4px 6px 8px #ff0000;

12.2.2 Box Shadow


CSS3 has the box-shadow property to add "drop shadows" to an element’s bounding box. The syntax of box
shadow property is similar to the text shadow, apart from the additional spread value. The first value is a
horizontal offset; that is, this value moves the shadow to the element’s right or the left. A positive number
moves the shadow to the right and a negative number moves the shadow to the left. The second value is the
vertical offset - the position of the shadow either above or below the element. A positive element places the
shadow below the bottom edge of the box, while a negative value moves the shadow above the top edge of
the box.

Example:

box-shadow: 10px 10px 8px 10px #888888;

Multiple Box Shadows


We can also add multiple box shadows to any element. To attach more than one shadow to an element, we
need to add a comma-separated list of shadows. In the following example, 3 box shadows are added to all the
elements with class name .mybox3

Example:

$ (“.content”) .prepend (‘some text’);

12.2.3 CSS Gradient


Gradients are combination of two or more colors. With CSS gradients we can display smooth transitions
between two or more specified colors.

There are two types of gradients in CSS

Linear Gradients: Linear gradients are used to arrange two or more colors in linear formats like top to
bottom, left to right etc

Example:
background: linear-gradient (to right, orange, yellow);
Other than “to right”, we can also use “to left”, “to top”, “to bottom” value depending upon which direction
we want the color combinations to go.

Diagonal Linear Gradient

You can even make the gradient run diagonally, from corner to corner.

The following example shows linear gradient that starts from top left to bottom right.

Example:

background: linear-gradient (to bottom right, red, orange);

Linear Gradient using Angle

We can get more control over the direction of the gradient, by defining an angle, instead of the predefined
directions (to bottom, to top, to right, to left, to bottom right, etc.).

The following example shows how to use angles on linear gradients:

Example:

background: linear-gradient (-90deg, red, yellow);

Radial Gradients: Radial gradient are used to arrange two or more colors emerge from a point and smoothly
spread outward in a circular shape.

Example:

background: radial-gradient (red 0, orange 45%, yellow 75%);

12.2.4 Transformations
CSS3 presents many properties that transform a web page element, by either rotating it, scaling it, moving it,
or distorting it along its horizontal and vertical axes. The basic CSS property to accomplish any of these
changes is the CSS transform property. You use this property by providing the type of transformation you
want and a value indicating how much to transform the element. For example, to rotate an element, you
supply the keyword rotate, followed by the number of degrees to turn it:

transform: rotate(10deg);

Scale
You can also resize an element, making it bigger or smaller using the scale function. For example, to make an
element twice as big, you add this declaration:

transform: scale (2);


The number you supply inside the parentheses is a scaling factor—a number that’s multiplied by the
element’s current size. For example, 1 is no scaling, 0.5 is half the current size, while 4 is four times the
current size.

Skew
Skewing an element lets you slant it on its horizontal and vertical axes: this can give an element a three-
dimensional feel. The skew function takes two values: the first specifies the horizontal movement and the
second the vertical movement. You can use values between 0deg to 360 deg.

transform: skew (25deg, 10deg);

Translate
The transform property’s translate function simply moves an element from its current position a set amount
left or right and up or down. By itself, it’s really not that useful. When a web browser transforms an element,
it doesn’t rearrange the page and the browser leaves an empty space where the tag would normally appear and
then draws the element in its new position.

The translate function takes two values: the first specifies the horizontal movement and the second the
vertical movement. You’re not limited to pixel values either. Any valid CSS length value — px, em, %, and so
on will work.

translate (1px, 2px);

12.2.5 Transition and Animation


Web designers have had few alternatives for creating animation for their website. The animated GIF provides
basic animation within an image. Adobe’s Flash program lets you create complicated animations, and even
games and web applications, but its learning curve is steep, and it can’t interact with the other HTML on your
page, like the images, headlines, and paragraphs that make up most web content. JavaScript lets you animate
anything on a web page, but at the cost of learning a full-fledged programming language. Thankfully, CSS3
gives a way to move, transform, and animate any HTML element on a page, without turning to any of those
other technologies.

Transitions
While transforms can be fun, they really bring your page to life when coupled with a CSS3 transition. A
transition is simply an animation from one set of CSS properties to another set over a specific amount of
time. For example, you can make a banner rotate 360 degrees over the course of two seconds.

To make a transition work, you need a few things in place:

1. Two styles: One style represents the beginning look of the element — a red button, for example —
while the second style is the ending look — a green button. The web browser will take care of the
process of animating the change between the two styles (changing the button from red to green, for
example).
.button {
Background-color: red;
}
.button : hover {
Background-color: green;
}

2. The transition property: CSS3 adds the transition property—the secret sauce that makes the
animation possible. In general, you apply the transition property to the original style, the style that
defines the look of an element before the animation begins.

.button {
background-color: red;
transition-property: background-color;
transition-duration: 1s;
}
.button: hover {
Background-color: green;
}

3. A trigger: The trigger is the action that causes the change between the two styles. With CSS, you can
use several pseudo-classes to trigger an animation. The most common is the :hover pseudo-class.
With it, you can animate the change between an element’s normal appearance and how it looks when
a visitor mouse over it.

Delaying a Transition’s Start


Finally, you can prevent a transition from animating right away with the transition-delay property. For
example, if you want to wait a half second before the animation begins, you can add this code:

transition-delay: .5s;

12.2 Check Your Progress

True or False

1. Translate function simply moves an element from its current position to new location.
2. Skewing an element lets you resize the elements
3. You can delay animation with transition-delay property

12.3 Summary

The text-shadow CSS property adds shadows to the text. Box shadow property is similar to the text shadow
property. Gradients are combination of two or more colors. With CSS you can add different types of
gradients. CSS3 has many properties that transform a web page element.
12.4 Check Your Progress Answers

12.2

1. True
2. False
3. True
Chapter 13

Introduction to Bootstrap 4

13.0 Objectives

13.1 Introduction

13.2 Getting Started with Bootstrap

13.2.1 Bootstrap Grid System

13.2.2 Bootstrap Content Classes

13.2.3 Bootstrap Components and Utilities

13.3 Summary

13.4 Check Your Progress Answers

13.0 Objectives

After studying this chapter you will be able to understand

- what is bootstrap

- how to install bootstrap

- how to use bootstrap grid

- how to use content, component and utility classes of bootstrap

13.1 Introduction
Bootstrap is an open source free front-end framework from Mark Otto and Jacob Thornton who, when it
was initially released, were both employees at Twitter. Since Bootstrap launched in August 2011, it has taken
off in popularity. It has evolved from being an entirely CSS-driven project to include a host of JavaScript
plugins that go hand in hand with forms and buttons. At its base, it allows for responsive web design and
features a robust 12-column.

13.2 Getting Started with Bootstrap


For someone starting a new project, Bootstrap comes with a handful of useful elements. With Bootstrap, you
just need to include the bootstrap.css CSS file and the bootstrap.js JavaScript file downloaded from https://
getbootstrap.com into your website and you are ready to go.

If you don’t want to download bootstrap file, you can alternatively use the CDN method as below to link
bootstrap files.
<link rel=”stylesheet”

href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css”>

<script

src=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js”></script>

Note: Make sure that you change the version number 4.0.0 to latest version in above links

13.2.1 Bootstrap Grid System


Grid systems enable you to create advanced layouts using rows and columns. The Bootstrap grid system can
have up to 12 columns, and you can specify how these columns scale for different viewport sizes.

The Bootstrap 4 grid system has five classes:


.col- (extra small devices - screen width less than 576px)
.col-sm- (small devices - screen width equal to or greater than 576px)
.col-md- (medium devices - screen width equal to or greater than 768px)
.col-lg- (large devices - screen width equal to or greater than 992px)
.col-xl- (xlarge devices - screen width equal to or greater than 1200px)

The classes above can be combined to create more dynamic and flexible layouts.

Things to Remember with Grids


• Rows must be placed within a .container (fixed-width) or .container-fluid (full-width) for proper
alignment and padding
• Use rows to create horizontal groups of columns
• Content should be placed within columns, and only columns may be immediate children of rows
• Columns create gutters (gaps between column content) via padding.
• Column widths are in percentage, so they are always fluid and sized relative to their parent element

Following is an example of 3 column grid for large and extra large screen

Example:

<div class=”container”>
<div class=”row”>
<div class=”colo-1g-4”>1 of 3 columns</div>
<div class=”col-1g-4”>1 of 3 columns</div>
<div class=”col-1g-4”>1 of 3 columns</div>
</div>
</div>
13.2.2 Bootstrap Content Classes
Bootstrap comes with pre built styles for typography, images, table etc. Here are some important styles:

Heading
Normal heading tags h1 through h6 work nicely most of the time. But there are times when you will need
larger font size for heading. Bootstrap has 4 different levels of display styles display-1 through display-4.

<h1 class=”display-1”>Display 1</h1>


<h1 class=”display-2”>Display 2</h1>
<h1 class=”display-3”>Display 3</h1>
<h1 class=”display-4”>Display 4</h1>

Typography

• text-lowercase: Converts text to lowercase


• text-uppercase: Converts text to uppercase
• text-capitalize: First letter of each word is capitalized.
• text-weight-bold: Bold without an explicit tag.
• text-weight-normal: Normal weight without an explicit tag
• text-italics: Italics without an explicit tag

You can use these styles as below:

<p class=”text- lowercase”>lowercase</p>


<p class=”text-uppercase”>uppercase</p>
<p class=”text-capitalize”>title case</p>

Images
With Bootstrap 4 you can make images responsive and change shape as well.

Responsive Images
When you use img-fluid class of Bootstrap 4 for any image, the image gets resized based on the screen size.
Images in Bootstrap are made responsive with max-width of image to 100% and height to auto.

<img src=”banner.jpg” alt=”banner” class=”img-fluid”>

Change Image Shape


Bootstrap allows you to apply three different shape styles to images
• img-rounded - will add round corners to your image
• img-circle - will crop your image into a circle
• img-thumbnail - will add round corners and a border to make the image look like a thumbnail
<img src=”round-image.jpg” class=”img-rounded” alt=”Image Rounded”>
<img src= “circle-image.jpg” class=”img-circle” alt=Image Circle”>
<img src=”thumbnail-image.jpg” class=”img-thumbnail” alt-Image Thumbnail”>

Table
The basic table structure can be easily set with the bootstrap class name “table”. By default it adds nice
padding and formatting to the content.

<table class=”table”>

</table>

13.2.3 Bootstrap Components and Utilities


Bootstrap component classes include alert boxes, breadcrumb, buttons, carousel, form, navbar etc.

Buttons

Buttons are one of the most commonly used components in Bootstrap. Bootstrap includes several predefined
button styles, each serving its own semantic purpose, with a few extras thrown in for more control. Bootstrap
class “btn” creates the basic button while other classes add extra features.

<button type=”button” class=”btn btn-primary”>Primary</button>

<button type=”button” class=”btn btn-secondary”>Secondary></button>

<button type=”button” class=”btn btn-success”>Success</button>

<button type=”button” class=”btn btn-danger”>Danger</button>

<button type=”button” class=”btn btn-warning”>Warning</button>

<button type=”button” class=”btn btn-info”>Info</button>

<button type=”button” class=”btn btn-light”>Light</button>

<button type=”button” class=”btn btn-dark”>Dark</button>

13.2 Check Your Progress

True or False

1. Bootstrap is an open source free front-end framework.


2. display-1 through display-4 classes are used to increase the font size of heading elements.
3. text-capitalize class converts text to uppercase
13.3 Summary

Bootstrap is an open source free front-end framework. Grid systems enable you to create advanced layouts
using rows and columns. Bootstrap comes with pre built styles for typography, images, table etc.

13.4 Check Your Progress Answers

13.2

1. True
2. True
3. False
Chapter 14

Introduction to JavaScript

14.0 Objectives

14.1 Introduction

14.1.1 Java and JavaScript: The Misunderstanding

14.1.2 Client Server Architecture

14.1.3 Adding JavaScript to HTML Page

14.1.4 “Hello World!” : First JavaScript Project

14.1.5 JavaScript Syntax

14.1.6 Comments

14.1.7 Reserved Words in JavaScript

14.2 Summary

14.3 Check Your Progress Answers

14.0 Objectives

After studying this chapter you will be able to understand

- what is JavaScript

- the difference between client and server

- JavaScript syntax

14.1 Introduction

JavaScript is a scripting language that enables you to supercharge your HTML with animation, interactivity,
and dynamic visual effects. Majority of the modern day websites use JavaScript, and all current web browsers-
on desktops, game consoles, tablets, and smart phones-contain JavaScript interpreters, making JavaScript one
of the most utilized programming language in the history. JavaScript is part of the triad of technologies that
all Web developers need to learn: HTML to define the content of web pages, CSS to specify the appearance
of web pages, and JavaScript to specify the behavior of web pages. On web pages it provides interactivity,
from basic animation effects to form validation to full-fledged single-page applications.

When JavaScript first came out in 1995, its primary goal was to deal with some of the input validation that
had previously been left to server-side languages such as Perl. Prior to that time, a round-trip to the server
was required to decide if a required field had been left blank or an entered value was invalid. Since that time,
JavaScript has expanded into an essential feature of every major web browser on the market.

JavaScript Features:

• JavaScript is a object-based scripting language


• It can validate user inputs
• It can perform simple mathematical calculations on the client side
• It can detect the user's browser and OS
• It can handle date and time
• It can be used for animation and visual effects
• Although Javascript is a client side language, now it can also be used as server side language
• It is a case sensitive language.

14.1.1 Java and JavaScript: The Misunderstanding

Plenty of people believe that JavaScript is similar to the Java language as it contains the name but it is not
true. JavaScript, in spite of the name, is essentially unrelated to the Java programming language, even though
both have the common C syntax, and JavaScript copies many Java names and naming conventions. The
language JavaScript was originally named "LiveScript" but was renamed in a co-marketing deal between
Netscape and Sun.

The JavaScript programming language, developed by Netscape, Inc., is not a product of the Java platform.
JavaScript does not create applets or stand-alone desktop applications. In its most common form, JavaScript
exists inside HTML documents, and can generate levels of interactivity to web pages that are not achievable
with plain HTML.

Key differences between Java and JavaScript:

• Java is a programming language while Java Script is a scripting language.


• Java creates applications that run on a computer while JavaScript code is run on a browser only.
• Java code needs to be compiled while JavaScript codes are all in text.

14.1.2 Client Server Architecture

Client-server is a software architecture model comprising two parts, client system and server system, both
interacting over a computer network. A client-server network is engineered for end-users, referred to as
clients, to gain access to resources such as files, songs, video collections, or some other service from a central
computer known as a server. A server's only purpose is to do what its name implies - serve its clients!

Client: Requests for resources over the network or internet. Clients include Web browsers, chat applications,
and email software etc.
Server: Listen to the clients requests and provide the desired resources (data, files, audio, video, images etc.)
to the clients over the network.

Differences between Client-side and Server-side Languages:

Website scripts run in one of two places - the client side, also known as the front-end, or the server side, also
known as the back-end. The client of a website refers to the web browser that is browsing it. The server of a
website is, obviously, the server that hosts it.

The majority of the web coding languages are designed to operate on either the server side or the client side.
This mainly defines how they work. Here are some examples.

Client Side Languages:

Client side development is carried out almost entirely in JavaScript. This is, obviously, in addition to basic
HTML and CSS code. The reason JavaScript is referred to as a client side language is mainly because it runs
scripts on your computer after you’ve loaded a web page.

Server Side Languages:

A server side or back-end language runs its scripts prior to the HTML is loaded, not after. There are a range
of server side languages in use on the web today. PHP is one of the most preferred, as well as Ruby on Rails,
ASP.NET and many more. They are referred to as server side languages mainly because their scripts are run
not on your computer, but on the server that hosts the website and delivers down the HTML code.

14.1.3 Adding JavaScript to HTML Page

The primary method of inserting JavaScript into an HTML page is via the <script> element. There are two
ways to use the <script> element: embed JavaScript code directly into the page or include JavaScript from an
external file.
To include inline JavaScript code, place JavaScript code inside the <script> element directly, as follows:

Example:

<script type=”text/javascript”>

Alert(“Hello!”);

</script>

To include JavaScript from an external file, the src attribute is required. The value of src is a URL linked to a
file containing JavaScript code, like this:

<script type=”text/javascript” src=”script.js”></script>

<script> Tag Placement

Traditionally, all <script> elements were placed within the <head> element on a page, such as in this
example:

<!DOCTYPE hmtl>

<html>

<head>

<title>Page Title</title>

<script type=”text/javascript” src=”script.js”></script>

</head>

<body>

<!- - content here -->

</body>

</html>

However, adding all JavaScript files in the <head> of a document means that all of the JavaScript code has
to be downloaded, parsed, and interpreted before the page starts rendering. For pages that require a lot of
JavaScript code, this can cause an obvious delay in page rendering, during that time the browser will be
entirely blank. For this reason, modern web developers mainly include all JavaScript references in the
<body> element, after the page content, as shown in this example:
<!DOCTYPE hmtl>

<html>

<head>

<title>Page Titiel</title>

</head>

<body>

<!- - content here - ->

<script type=”text/javascript” src=”script.js”></script>

</body>

</html>

14.1.4 “Hello World!”: First JavaScript Project

Here is a simple Hello World example of using JavaScript. If you run this program, you will get an alert
message “Hello, world!”

<!DOCTYPE html>

<html>

<head>

<title>Hello World Example </title>

</head>

<body>

<p>Some Content Here</p>

<script>

alert (“Hello, world !”);

</script>

<body>

</html>
14.1.5 JavaScript Syntax:

JavaScript borrows most of its syntax from Java, but also inherits from languages like Awk and Perl.

Case Sensitivity:

JavaScript is a case-sensitive language. It indicates that the language keywords, variables, function names, and
any other identifiers must always be typed with a consistent capitalization of letters. So the identifiers myVar
and MYVAR will convey different meanings in JavaScript. Care should be taken while writing variable and
function names in JavaScript.

White Space and Semicolons:

Spaces, tabs and newlines used outside of string constants are called whitespace. JavaScript ignores spaces,
tabs, and newlines that appear in JavaScript programs. You can use spaces, tabs, and newlines freely in your
program and you are free to format and indent your programs in a neat and consistent way that makes the
code easy to read and understand.

Semicolon is optional at the end of the statement, although it is good practice to use it to avoid undesired
results.

14.1.6 JavaScript Comments:

JavaScript supports both C-style and C++-style comments:

• Any text between a // and the end of a line is treated as a comment and is ignored by JavaScript.

• Any text between the characters /* and */ is treated as a comment. This may span multiple lines.

Example:

<script type=”text/javascript”>

// This is a comment. It is similar to comments in C++

/*

* This is a multiline comment in JavaScript

* It is very similar to comments in C programming

*/

</script>
14.1.7 Reserved Words in JavaScript:

JavaScript reserves a number of identifiers as the keywords of the language itself. You cannot use these words
as identifiers in your programs: break, delete, function, return, typeof, case, do, if, switch, var, catch, else, in,
this, void, continue, false, instanceof, throw, while, debugger, finally, new, true, with, default, for, null, try

14.1 Check Your Progress

True or False

1. JavaScript is a scripting language.


2. JavaScript is a case-sensitive language
3. JavaScript does not ignore white spaces, tabs, and newlines

14.2 Summary

JavaScript is a scripting language that helps you add animation, interactivity, and dynamic visual effects to
HTML document. Java and JavaScript are two completely different languages. Traditionally JavaScript was
regarded as client side languages, but due to recent developments it can also be used as server side language.
JavaScript is a case sensitive language.

14.3 Check Your Progress Answers

14.1

1. True
2. True
3. False
Chapter 15

Working with Variables and Data Types

15.0 Objectives

15.1 Introduction

15.2.1 Data Types in JavaScript

15.2.2 Working with Numbers

15.2.3 Working with Strings

15.2.4 Understanding Booleans Values

15.2.5 Difference between Undefined and Null

15.3 Arrays

15.3.1 Object

15.4 Summary

15.5 Check Your Progress Answers

15.0 Objectives

After studying this chapter you will be able to understand

- the meaning of variable and its data types

- the concepts of array and object

15.1 Introduction

Variables can be seen as named containers. You can set data into these containers and then refer to the data
simply by naming the container. Before you use a variable in a JavaScript program, you have to declare it.
JavaSctipt variables are loosely typed, which means that a variable can hold any type of data. Every variable is
just a named placeholder for a value. To define a variable, use the var keyword followed by the variable name.

Example:

var message;

Assigning Value to Variable:

This code defines a variable named message that can be used to hold any value. Without initialization, it has
the special value undefined. It is possible to define the variable and set its value at the same time, as in this
example:
var message = “Welcome”;

Here, variable name message is defined to hold a string value of "Welcome".

15.1.1 Data Types in JavaScript:

We manage distinct types of information every day e.g. name, age, price of product, address, date.
Programming languages classify this information into different types, and treat each type in a different way. In
JavaScript, there are three primary data types, two composite data types, and two special data types.

1. Primary Data Types


• Number
• String
• Boolean

2. Composite Data Types


• Object
• Array

3. Special Data Types


• Undefined
• Null

15.1.2 Working with Numbers:

Numbers are used for counting and calculating. Unlike many languages, JavaScript does not make a
distinction between integer values and floating-point values.

Integer Values

Integer values can be positive whole numbers, negative whole numbers, and 0.

Floating-point Values

Floating-point values can be whole numbers with a decimal portion e.g. 12.77

Example:

var age = 22;

var price = 19.95;

Mathematical Operations:

Holding a particular piece of information such as a number in a variable is generally a first step in a program.
In JavaScript you can manipulate data to obtain new results. For example, you can add a number to a score to
increase it or perform other arithmetic operations like subtraction, multiplication or division.
Basic Math

JavaScript supports basic mathematical operations such as addition, division, subtraction, and so on.

Operator What it does? How to use it?


+ Addition 15+20 = 35
- Subtraction 15-3 = 12
* Multiplication 5*3 = 15
/ Division 21/3 = 7
% Modulus Operator (Remainder) 20 % 3 = 2

Example:

var price = 10;

var quantity = 15;

var totalCost = price * quantity;

alert (totalCost);

//output : 150

15.1.3 Working with Strings:

To store a name, a sentence, or any series of letters, you make use of strings. A string is just a series of
characters (letters and other symbols) enclosed inside of quote marks. For example, 'Welcome!', and "John
Smith" are both examples of strings. A string’s opening quote mark explains the JavaScript interpreter that
what follows is a string. You can use either double quote marks "hello world" or single quote marks 'hello
world' to enclose the string, but you need to make sure to use the same type of quote mark at the starting and
end of the string.

Example:

var myName = “John Smith”;

alert(myName);

//output : John Smith

Concatenate Strings:

One of the many built-in features of JavaScript is the ability to concatenate strings. If you use the + operator
with numbers, it adds them. But if you use this operator on strings, it joins them by appending the second to
the first.
Example:

var message = “Welcome!”;

var user = “John Smith”;

alert(message + “ ” + user);

//output : Welcome! John Smith

15.1.4 Understanding Booleans Values:

A boolean value represents true or false, on or off, yes or no. There are only two possible values of this type.
Boolean values are generally the result of comparisons you make in your JavaScript programs.

Example:

var a= true;

15.1.5 Difference between Null and Undefined

Undefined:

Undefined value means a variable has been declared but has not yet been assigned a value.

Example:

var age = 15; //defined

var username; //undefined

Null:

null is an assignment value. It can be assigned to a variable as a representation of no value.

Example:

var education = null;

15.1 Check Your Progress

Fill in the blank

1. Without initialization, variable has the special value ________.


2. A _______ value represents true or false.
15.2 Arrays:
Basic variables, like the ones you learned in the previous section, hold only one piece of information, such as
a number or a string value. They’re best suited when you only require keeping track of a single thing like a
score, an age, or a total cost. But, if you need to keep a count of a group of related items - like the names of
all of the days in a week, basic variables is not a very convenient option.

To create and store items in an array, you first declare the array’s name (just as you would a variable) and then
provide a list of comma-separated values: each value presents one item in the list. To create an array, you put
the list of items between opening and closing brackets: [ ].

Example:

var days =[‘Mon’, ‘Tues’ ‘Wed’, ‘Thus’, ‘Fri’, ‘Sat’, ‘Sun’];

Accessing Items in an Array

You can get access to the contents of a basic variable just by using the variable’s name. But, because an array
can hold more than one value, you can’t just use its name alone to access the items it contains. A number,
called an index, displays the position of each item in an array. To obtain a particular item in an array, you use
that item’s index number. Arrays are zero-indexed, meaning that the first item in an array has an index value
of 0, and the second item has an index value of 1.

Example:

var days = [‘Mon’, ‘Tues’, ‘Wed’, ‘Thus’, ;Fri’, ‘Sat’, ‘Sun’];

alert(days[0]);

//output : Mon;

15.2.1 Object:

The real life is full of objects, like a car or a dog. Many objects are made up of different parts: A dog has a tail,
a head, and four legs; a car has doors, wheels, headlights, and a horn. An object might also do something - a
car can transport passengers, a dog can bark.

The world of JavaScript is also full of objects: a browser window, a document, and a date are a few examples.
Like real-world objects, JavaScript objects are also made up of different parts. In programming language, the
parts of an object are known as properties. The actions an object can carry out are referred to as methods or
functions.

Every object in JavaScript possesses its own set of properties and methods. To access an object’s property or
execute one of its methods, you use dot syntax.

For example, document.write() means "run the write() method of the document object."
15.2 Check Your Progress

Fill in the blank

1. _____ holds list of comma-separated values

15.3 Summary

Variables are named containers. You can set data into these containers and then refer to the data simply by
naming the container. String, number, boolean, object, array, null and undefined are data types in JavaScript.
Variables store single piece of information while array store list of comma separated values.

15.4 Check Your Progress Answers

15.1

1. Undefined
2. Boolean

15.2

1. Array
Chapter 16

Conditions and Loops

16.0 Objectives

16.1 Introduction

16.2 If Statements

16.2.1 Comparison Operators

16.2.2 If-else Statements

16.2.3 If-else-if Statements

16.2.4 Switch Case

16.3 Loops: Minimizing Repetition

16.3.1 While Loops

16.3.2 Do-While Loops

16.3.3 For Loops

16.4 Summary

16.5 Check Your Progress Answers

16.0 Objectives

After studying this chapter you will be able to understand

- if, if-else and if-else-if statements

- switch statement

- what is loop and different types of loops

16.1 Introduction

Usually when you write code, you want to do different actions for different decisions. You can use
conditional statements in your code to accomplish this.

16.2 If Statement

The “if” Conditional statements perform a task only if the answer to a question is true:
if ( condition ){

// some action happens here

There are three parts to the statement: “if” indicates that the programming that follows is a conditional
statement; the parentheses enclose the yes or no question, known as the condition; and the curly braces ({ })
mark the start and end of the JavaScript code that should execute if the condition is true.

Example:

if (score >= 35) {

alert (‘Successful !’);

16.2.1 Comparison Operators

Comparison Operator What It Means


== Equal to
!= Not equal to
=== Strict equal to
!== Strict not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

16.2.2 If-else Statements:


The simple conditional statement in the previous section doesn’t have a backup plan for a condition that
turns out to be false. The second form of the “if” statement presents an else clause that is executed when
expression is false. Its syntax is:

Example:

if ( condition ) {

//statement 1

} else{

//statement 2

}
This form of the statement executes statement 1 if expression is true and executes statement 2 if expression is
false.

16.2.3 If-else-if Statements:

The if/else statement examines an expression and executes one of the two pieces of code, based on the
outcome. But what about, when you need to execute one of many pieces of code? One way to do this is with
an else if statement.

Example:

if (a ==1) {

//Execute statement 1

else if (a == 2) {

//Execute statement 2

else if ( a == 3){

//Execute statement 3

else {

// If all else fails, execute statement 4

16.2.4 Switch Case:

Switch statement is closely related to the “if” statement. The syntax for the switch statement in JavaScript is
similar to the syntax in other C-based languages:
Switch (expression) {

case value :

statement

break;

case value :

statement

break;

case value :

statement

break;

case value :

statement

break;

default : statement

Every case in a switch statement says, “If the expression is equal to the value, execute the statement.” The
break keyword triggers code execution to jump out of the switch statement. The default keyword implies
what is to be done if the expression does not evaluate to one of the cases.
var color = “Yellow”;

switch (color) {

case ‘Blue’:

alert (“Blue”);

break;

case ‘Yellow’

alert (“Yellow”);

break;

case ‘Red’

alert (“Red”);

break;

default :

alert (“Unknown Color”);

16.2 Check Your Progress

True or False

1. "!=" is “not equal to” operator in JavaScript


2. The “if” Conditional statements perform a task only if the answer to a question is true
3. else clause of if - else statement is executed when expression is false

16.3 Loops: Minimizing Repetition


Quite often a script requires repeating the same series of steps over and over again. In programming
converse, executing the same task over and over is called a loop, and because loops are so common in
programming, JavaScript provides several different types. All do the same thing, just in just a little different
ways.

16.3.1 While Loops:


A while loop repeats a chunk of code as long as a particular condition is true; in other words, while the
condition is true. The basic structure of a while loop is this:

while (condition) {
// do something
}
The first line presents the while statement. Just like a conditional statement, you place a condition between
the set of parentheses that follow the keyword while. The condition is any test you’d use in a conditional
statement, such as i <=3.

But, contrary to a conditional statement, when the JavaScript interpreter reaches the closing brace of a while
statement, rather than moving forward to the next line of the program, it gets back to the top of the while
statement and tests the condition a second time. If the condition is yet again true, the interpreter runs the
JavaScript code between the braces a second time. This process carries on till the condition is no longer true;
then the program moves on to the next statement following the loop.

Example:

var i = 1;

while (i <=3){

document.write (‘Value of i is: ‘ + i + ‘<br>’);

i =i + 1;

The first line of code var i = 1; isn’t part of the while loop: Rather, it creates a variable to hold the number.
The second line is the start of the loop. It sets up the test condition. So long as the number stored in the
variable "i" is less than or equal to 3, the code between the braces runs. When the test condition is tested for
the first time, the value of i is 1, so the test is true (1 is less than 3), and the document.write() command
executes, writing “Value of i is: 1” to the page (the <br> is just an HTML line break to ensure each line prints
onto a separate line on the web page).

The last line of the loop “ i = i+1;” is very important. It increases the value of variable i by 1. This process
continues until the condition is no longer true; that is when the value of variable i becomes more than 3. Just
after the value of variable i becomes 4 the program exits the while loop.

Note: You can use i++; instead of i = i +1;

16.3.2 Do-While Loops:

There exists one more, less common type of loop, named a “do while” loop. This type of loop works nearly
in the same ways to a while loop. Its basic structure looks like this:

do{

// javascript to repeat

} while ( condition );
In this kind of loop, the conditional test occurs at the end, after the loop has run. Because of this, the
JavaScript code within the curly braces always runs at least once. Even if the condition isn’t ever true, the test
isn’t performed until after the code runs once. There aren’t too many cases where "do while" is useful.

var i = 0;

do {

i = i + 1;

alert ( i );

} while ( i <= 3);

16.3.3 For Loops:

A for loop is usually used in the same way a while loop is, particularly, to execute code a certain number of
times. You use a “for” loop to generate a loop in which the conditions are initialized, evaluated, and changed
in a efficient form. Here’s an example:

for (var i = 1; i <= 3; i ++){

alert ( i );

A for statement has three clauses in parentheses. The first clause sets the primary expression, as shown in the
preceding example and also here:

var i= 1;

The next clause of a “for” statement identifies the test expression, displayed by the following code from the
example:

i <= 3;

The final expression is generally used to increment the counter used for the test. In the code example, this
expression is the final clause in the parentheses:

i ++;
Check Your Progress

True or False

1. A while loop repeats a chunk of code as long as a particular condition is true

16.4 Summary

Conditional statements are used to decide the flow of execution based on different conditions. If a condition
is true, you can perform one action and if the condition is false, you can perform another action. There are
three JavaScript conditional statements – if statement, if/else statement, if-else-if statement. You should use
loops when you want to run series of steps over and over again. “For loop” and “while loop” are popular
loops in JavaScript.

16.5 Check Your Progress Answers

16.2

1. True
2. True
3. True

16.3

1. True
Chapter 17

Functions: Writing Code for Later

17.0 Objectives

17.1 Introduction

17.1.1 Arguments: Passing Data to Functions

17.1.2 Return Statement: Outputting data from function

17.1.3 Function Scope

17.2 Summary

17.3 Check Your Progress Answers

17.0 Objectives

After studying this chapter you will be able to understand

- how to define function

- how to invoke function

- how to pass data to function and receive back the return value

- variable scope inside and outside function

17.1 Introduction

So far, all the JavaScript code we’ve seen executes as soon as the page loads in your browser. It runs from top
to bottom and then stops, never to run. Quite often, we’ll want to execute different parts of our program at
different times, or re-run the same code quite a few times. In order to do this, you have to put your code into
functions.

Functions are like little packages of JavaScript code waiting to be called into action. A function can essentially
be seen as a wrapper for a block of code. All you need to do is name that block, and you’ll be able to call it
from other areas of your program, whenever you like.

You can define your own functions using the function keyword. This tells the program that you’re defining a
new function, and that the code contained between the curly braces that follow should be executed whenever
that function is called.

function message (){

alert (“Welcome to Our Site !”);

}
Although the function message is declared above, the code inside it won’t get executed till you invoke it.

Invoking Function:

Calling, or invoking, the function is as simple as:

message ();

Functions are perfect when you have something that needs to happen multiple times within a program.
Rather than defining the same code multiple times, you can use a function.

17.1.1 Arguments: Passing Data to Functions:

Functions can accept arguments, which are input values passed into the function. Within a function, those
arguments passed into the function can be acted upon and the results returned to the caller of the function
via a return value.

Arguments are passed to a function within the parentheses of the function definition. Here’s a brief example
of using function arguments:

function myFunction (argument1, argument2){

//Do something

You pass values to this function as below:

myFunction (val1, val2);

Example:

function message (username, userMessage){

alert (username + “ “ + userMessage );

message (“John”, “Welcome to our site !”);

//output : John Welcome to our site !

In the above example, the function “message” accepts two arguments userName and userMessage. These two
arguments are then displayed through alert function. On the last line function “message” is invoked passing
two values to the function.

17.1.2 Return Statement: Outputting data from function:

Thus far, the outcome of most of our functions has been to display an alert box to the user with a message in
it. But most of the time, you’ll want your functions to be silent, simply passing data to other parts of your
program. A function may return data to the statement that called it. The neat thing about that is that you can
assign a function call as the value of a variable, and that variable’s value will become whatever was returned
by the function.

To get a function to return a value, we use the return keyword, followed by the value we want it to return:

Example:

var sumTotal;

function sum(num1, num2){

return num1 + num2;

sumTotal = sum ( 3, 4);

alert (sumTotal);

// output: 7

In the above example, first we have declared 1 variable to store the returned value of function. Then we have
declared a function named “sum”. The “sum” function accepts 2 arguments. It then adds the two arguments
and returns back the total. Till now nothing happens as we have not yet invoked or called the function. On
the next line we have invoked the “sum” function and passed 2 values to process. The result returned back by
“sum” function is stored in the variable sumTotal. On the last line the value in sumTotal variable is displayed
through alert function.

17.1.3 Function Scope:

In JavaScript there are two types of scope local scope and global scope. Each JavaScript function creates a
new scope. Variables defined inside a function are not accessible from outside the function. Variables
declared within a JavaScript function, become LOCAL to the function. Local variables have local scope: They
can only be accessed within the function.

function myFunction( ){

var country = “India”;

}
A variable declared outside a function, becomes GLOBAL.

var country = “India”;

function myFunction( ){

17.1 Check Your Progress

Fill in the blank

1. Variable declared inside function has global scope.


2. Code inside the function does not get executed till the function is invoked.

17.2 Summary

Functions are like little packages of JavaScript code waiting to be called into action. By merely defining the
function the code inside the function does not automatically execute. You need to invoke the functions to
execute it. Function accepts parameter and returns value. Variable defined inside a function has local scope,
while variable defined outside the function has global scope.

17.3 Check Your Progress Answers

17.1

1. False
2. True
Chapter 18

DOM: Document Object Model

18.0 Objectives

18.1 Introduction

18.1.1 Finding Elements by Tag Name

18.1.2 Finding Elements by Class Name

18.1.3 Finding Elements by Id

18.1.4 Finding Parent

18.1.5 Finding Children

18.1.6 Finding Siblings

18.1.7 Interacting with Attributes

18.1.8 Changing Styles

18.2 Summary

18.3 Check Your Progress Answers

18.0 Objectives

After studying this chapter you will be able to understand

- the meaning of DOM

- how to find elements

- change style of elements

18.1 Introduction

The DOM represents HTML documents in a tree-like structure — or rather, an uprooted treelike structure
because the root of the tree is on top.

Inside DOM model each element in the HTML document becomes an object, as do all the attributes and
text. JavaScript can access each of these objects independently, using built-in functions that make it easy to
find and change what we want on the fly. Due to the way in which HTML is written-as a hierarchy of nested
elements marked with start and end tags-the DOM creates a different object for each element, but links each
element object to its enclosing (or parent) element. This produces an explicit parent-child relationship
between elements, and lends the visualization of the DOM most readily to a tree structure. The Document
Object Model provides a way to access and alter the contents of Hypertext Markup Language (HTML)
documents. The DOM is a standard defined by the World Wide Web Consortium (W3C).

<html>

<head>

<title>Hello World</title>

</head>

<body>

<div>Some Content Here</div>

<p>Link to the <a href=”http://www.google.com”>Google</a></p>

</body>

</html>

Nodes:

To generate the DOM for a document, every element in the HTML is displayed by what’s known as a node.
A node’s position in the DOM tree is determined by its parent and child nodes. An element node is
recognized by its element name (head, body, h1, etc.).
The elements inside the tree structure are sometimes referred to as nodes or node objects. Nodes at the level
under a given node are known as children. For example, the <body> node is said to be a parent of the <p>
nodes. Any nodes under a given node are known as descendants of that node.

18.1.1 Finding Elements by Tag Name:

Finding the elements of a document is an essential way you use the DOM when programming with
JavaScript. The document.getElementsByTagName() method selects every instance of a particular tag -
document.getElementsByTagName('a'), for example, selects all anchor tags on a page;

var myAnchors = document . getElementsByTagName (“a”);

You could then examine the properties of the “a” elements stored in the myAnchors variable by looping
through them.

18.1.2 Finding Elements by Class Name:

The getElementsByClassName() method returns a collection of all elements in the document with the
specified class name.

var myClass = document . getElementsByClassName (“mytitle”);

18.1.3 Finding Elements by Id:

The getElementById() method is a workhorse method of the DOM. It retrieves a specified element of the
HTML document and returns a reference to it. To retrieve an element, it must have an id attribute.

var a1= document . getElementById (“about-us”);

18.1.4 Finding Parent:

Every element node — except for the document node — has a parent. Consequently, each element node has
a property called parentNode. When we use this property, we receive a reference to the target element’s
parent.

Once we have a reference to the element, we can get a reference to its parent using parentNode like so:

var x = document . getElementById(“main”). parentNode;

18.1.5 Finding Children:

The parent-child relationship isn’t just one way. You can discover all of the children of an element applying
the childNodes property. An element can only have one parent, but it can have many children, so childNodes
is in fact a node list that contains all of the element’s children, in source order.

var y = document . getElementById(“main”) . childNodes;

You can get first child and last child in above example as below:
var z = y.firstChild;

var k = y.lastChild;

18.1.6 Finding Siblings:

As well as moving up and down the DOM tree, we can move from side to side by getting the next or
previous node on the same level. Continuing with the last example, we can use nextSibling and
previousSibling to do so.

var b = y . nextSibling;

var c = y . previousSibling;

18.1.7 Interacting with Attributes:

Attributes like width, height, src etc. are localized to the elements they’re associated with-they don’t have
much significance in the bigger scheme of things. So, we don’t have DOM functions that will let you get a
particular attribute node, or all attributes with a certain value. DOM only provides two methods related to
attributes, and both of them can only be used when you you have an element reference.

Getting an Attribute

With a reference to an element already in hand, you can get the value of one of its attributes by calling the
method getAttribute with the attribute name as an argument.

var a1 = document . getElementById(“current-link”) . getAttribute (“href”);

Setting an Attribute

As well as being readable, all HTML attributes are writable via the DOM. To write an attribute value, we use
the setAttribute method on an element, specifying both the attribute name we want to set and the value we
want to set it to:

document . getElementById (“about-us”) . setAttribute (“href”, “/about . html”);

18.1.8 Changing Styles:

Nearly all aspects of your web page are accessible via the DOM, including the way it looks. Each element
node has a property called style. style is a deceptively substantial object that lets you change every aspect of an
element’s appearance, from the color of its text, to its line height, to the type of border that’s drawn around it.
For every CSS property that’s relevant to an element, style has an identical property that enables you to
change that property’s value. To change the text color of an element, we’d use style.color:

var b1 = document . getElementById(“headline”);

b1 . style . color = “#FF0000”;


18.1 Check Your Progress

True or False

1. The document.getElementsByTagName() method selects every instance of a particular tag


2. Each element in the HTML document is an object
3. A node’s position in the DOM tree is determined by its parent and child nodes.
4. Every element node in DOM has a parent

18.2 Summary

Document Object Model provides a way to access and alter the contents of HTML. You can find the element
by getElementsByTagName, getElementsByClassName, getElementById in JavaScript. You can also find
parent, child and sibling of element.

18.3 Check Your Progress Answers

18.1

1. True
2. True
3. True
4. False
Chapter 19

JavaScript Events

19.0 Objectives

19.1 Introduction

19.1.1 Handling Window Events

19.1.2 Working with Mouse Events

19.1.3 Form Events Handling

19.1.4 Dealing with Key Events

19.2 Summary

19.3 Check Your Progress Answers

19.0 Objectives

After studying this chapter you will be able to understand

- what is JavaScript event

- window, mouse, form and keyboard events

19.1 Introduction
Events are actions that the user performs while visiting your page. When the browser detects an event, such
as a mouse click or a key press, it can trigger JavaScript objects associated with that event, called event
handlers.

19.1.1 Handling Window Events


Window events occur when the user does something affecting an entire browser window. The most common
window event is simply loading the window by opening a particular Web page. You can also have events that
trigger event handlers when windows are closed, moved, or even sent to the background.

The onload Event


It is triggered when the user enters your page and all its elements have completed loading the page.
Example:

<body onload= “myFunction( ) “>

The onunload Event


The onunload event occurs once a page has unloaded (or the browser window has been closed).
Example:
<body onunload= “myFunction ( ) “>

The onresize Event


The onresize event occurs when the browser window has been resized.
Example:

<body onresize = “myFunction ( )”>

19.1.2 Working with Mouse Events


The onclick event
The onclick event occurs when the user clicks on an element. The click event includes the mousedown and
mouseup events.
Example:

<input type= “button” value=”Click Me” onclick=”alert (‘You Clicked !’) “>

The onmousedown event


The onmousedown event occurs when a user presses a mouse button over an element.
Example:

<p onmousedown=”alert (‘Mouse Down’)”>Click And Hold</p>

The onmouseup event


The onmouseup event occurs when a user releases a mouse button over an element.
Example:

<p onmuseup= “alert (‘Mouse Up’) “>Click, Hold And Release </p>

The onmousemove event


The onmousemove event occurs when the pointer is moving while it is over an element.
Example:

<div onmousemove=”alert (‘Moved !’)”>Move the cursor ove me</div>

The onmouseover event


The onmouseover event occurs when the mouse pointer is moved onto an element, or onto one of its
children.
Example:

<div onmousemove=”alert (‘Mouse Over Me’)”>Move Mouse Over Me</div>

The ondblclick event


The ondblclick event occurs when the user double-clicks on an element.
Example:
<p ondblick=”You Double Clicked”>Double-click me</p>

19.1.3 Form Events Handling


You need to use form event handling mainly for validating forms. With the events listed below, you can deal
with just about any action the user takes with forms.
The onsubmit event
The onsubmit event occurs when a form is submitted.
Example:
<form onsubmit=”myFunction ( )”>

</form>

The onreset event


The onreset handler is triggered when the user clicks the Reset button.
Example:

<form onreset=”myFunction ( )”>

</form>

19.1.4 Dealing with Key Events


Besides the mouse, the other main input device is the keyboard. Just as with the mouse, JavaScript has the
many keyboard events to handle the keyboard.
The onkeydown event
The onkeydown event occurs when the user is pressing a key

Example:

<input type=”text” onkeydown=”alert(You have pressed a key down’)”>

The onkeyup event


The onkeyup event occurs when the user releases a key (on the keyboard).

Example:

<input type=”text” onkeyup=”alert(‘You have released a key’)”>

The onkeypress event


The onkeypress event occurs when the user presses a key (on the keyboard).
Example:
<input type=”text” onkeypress=”myFunction( )”>

19.1 Check Your Progress

True or False
1. The onunload event occurs once a page has resized.
2. The onmouseup event occurs when a user releases a mouse button over an element.
3. The onkeypress event occurs when the user presses a key

19.2 Summary

Events are actions that the user performs while visiting your page. There are four major types of events in
JavaScript – window event, mouse event, form event, keyboard event.

19.3 Check Your Progress Answers

19.1

1. False
2. True
3. True
Chapter 20

JavaScript Events

20.0 Objectives

20.1 Introduction

20.1.1 Using jQuery

20.1.2 The $() factory function

20.2 Selecting and Manipulating Elements

20.2.1 Get and Set DOM Element Content

20.2.2 Styling Elements

20.2.3 Handling Events

20.3 Summary

20.4 Check Your Progress Answers

20.0 Objectives

After studying this chapter you will be able to understand

- what is jQuery

- how to use the factory function $()

- how to select and modify DOM elements

- how to style elements with jQuery

- how to handle events with jQuery

20.1 Introduction

jQuery is a fast, efficient, feature rich and most widely used JavaScript Library developed by John Resig in
2006 with a goal of writing less and doing more. jQuery makes a web developer's life easy. It provides many
built-in functions which simplifies DOM manipulation, event handling, web animation, and Ajax interactions
for rapid web development. jQuery is not a language but a JavaScript toolkit designed to simplify various
tasks by writing less code.

What can you do with jQuery?

jQuery aims to make JavaScript coding easier and more productive. Here is a list of important jQuery
features:
• DOM Selection: jQuery provides selectors to select DOM elements based on element tag, id, class
name, attribute name, value, etc.
• DOM Manipulation: jQuery makes it easy to select DOM elements, modify their content.
• Event Handling: With the help of jQuery, you can capture a wide variety of events, such as clicking
on a link.
• Animation: jQuery has plenty of built-in animation effects such as show, hide, fade-in, fade-out etc.
• Cross Browser Support: jQuery automatically takes care of JavaScript related cross browser issues. It
works well in IE6+, FireFox2+, Safari 3+, Chrome and Opera 9+.
• AJAX: With jQuery, you can easily use AJAX functionality to load data from server without
reloading the whole page.

Advantages of using jQuery:

JQuery has been a blessing for web developers be it experienced and newbie. The use of JQuery has several
benefits which include:

• Easy to learn: This is the main advantage of using jQuery. It has coding syntax similar to JavaScript.
• Easy to use: One of the goals of jQuery is to make the difficult tasks in JavaScript simple. jQuery
requires less lines of code to achieve the same result as compared to pure JavaScript code.
• Small File Size: The minified version of jQuery is only 84kb in size, which may be smaller than
single photo on a website.
• Documentation and Community Support: jQuery website has extensive documentation and
tutorials to get started.
• Extensible: jQuery comes with plugin framework, which makes it easy to extend jQuery.

20.1.1 Using jQuery

There are two ways to get jQuery:

1. Download jQuery file: This is the most common method of using jQuery.

Step 1: Download latest compressed version of jQuery file from https://jquery.com/download to


your local machine inside your “js” folder of website code.

Step2: Include jQuery file in HTML code as below

Example:

<script type=”text/javascript” src=”js/jquery . 3 . 1 . min . js”></script>

Note: The jQuery version used in this example is 3.3.1. Change the version name based on the latest version
you have downloaded.

2. Without downloading file: Another method is to reference a jQuery file in our HTML code directly
from Content Delivery Network (CDN) sites like Google, Microsoft, jQuery etc. Google hosts several
popular, open-source libraries on its CDN, including jQuery. So instead of hosting the jQuery file on our
own web server as we did in previous example, you can let google host the jQuery file.
Example:

<script src=http://ajax . googleapis . com/ajax/libs/jquery/3 . 3 . 1/jquery . min . js></script>

Note: jQuery file should be included before any script tag.

Uncompressed vs Compressed jQuery File:


On jQuery website, jQuery library file is available for download in two formats, compressed (also known as
minified or development version) and uncompressed (also known as production version). The source code of
compressed jQuery file is minified: spaces, line breaks and comments are removed. This is preferred version
of jQuery for live sites. Because of its smaller size it loads quickly and saves bandwidth. The downside of
compressed version is that it is almost impossible to read the code manually. The uncompressed version of
jQuery file is human readable and suits for development stage.

20.1.2 The $() factory function


By including jQuery in our web page we get access to a single magical function called jQuery. This single
function acts as gateway to entire jQuery library. The dollar sign ($) is the alias for jQuery. So you can either
use jQuery() or $().

Before we can interact with HTML elements on a page, we first need to make sure that those elements have
been loaded. $(document).ready is an event which fires up when document is ready. Whenever we use jQuery to
manipulate our web page, we must wait until the document ready event has fired. All the jQuery code should
be inside the document ready() method:

$(document) . ready (function ( ){


//jQuery code goes here
});

Example:

<script type=”text/javascript”>
$(document) . ready (function ( ) {
Document.wirte (“Hello World”);
});

</script>

jQuery Syntax

jQuery syntax consist of two parts.


a. Selection of the element to be processed
b. Some action on the selected element

$ (selector) . action ( )

Here are some practical examples

$ (“ p”) . hide ( );

$ (“.example”) .css(“background-color”,”red”);
20.1 Check Your Progress

True or False

1. jQuery is a JavaScript Library.

20.2 Selecting and Manipulating Elements

Now that we are familiar with the basic jQuery syntax, let’s dive deep into selecting elements on the page. In
JavaScript, we used getElementById() and getElelementsByTagName() to select elements in a document.
Unfortunately, these two methods don’t provide us needed control to select elements. Fortunately, jQuery
has very powerful technique for selecting and working on the page elements with CSS selectors.

Selectors: To work with an element on the web page, first we need to find them. To find the html
element in jQuery we use selectors.

1. Selecting element by Tag Name: We can select all <p> tags with following code

$ (“p”)

Here are few more examples

$ (“div”) //selects all div elements in the document


$ (“div”) // selects all images in the document
$ (“a”) // selects all anchor tags in the document

2. Selecting element by ID: The jQuery #id selector uses the id attribute of an HTML tag to find the
specific element.

Following code selects element with the id “header”

$ (“#header”)

3. Selecting element by class name: The jQuery class selector finds elements with a specific class.
Following code selects all elements with class name “entry-title”

$ (“.entry-title”)

4. Universal selector: (*) selects all elements in the available document

$(“*”)

5. Multiple elements selector: We can select multiple elements as follows

$ (“div, p, .entry-content”)
This will select all <div> tags, <p> tags and elements with class name “entry-content”

20.2.1 Get and Set DOM Element Content

jQuery has powerful methods for manipulating HTML elements and attributes. Following are the 3 most
useful methods of jQuery for DOM manipulation:

text() method: The text() method sets and gets the text content of all the selected elements

Example:

var textContent = $ (“h1”) . text ( );


alert(textContent);

text() returns only the content inside the selected element.

html() method: The html() method sets and gets the html content of all the selected elements

Example:

var htmlContent = $ (“p”) .html ( );


alert (htmlContent);

html() method returns not just the content inside selected element but also other elements as well.

val() method: The val() method sets and gets the value of form field

Example:

var inputValue = $ (“#fname”) . val ( );


alert (inputValue);

The value of the input box is stored in the variable “inputValue” and then alert message displays it.

Add DOM Content: We can easily add or remove DOM element contents with jQuery.

Here are four jQuery methods that are used to add new content:

append(): With this method we can add content (inside) at the end of the selected elements

Example:

$ (“ . content”) . append (‘add me at the end’);

prepend():With this method we can add content (inside) at the beginning of the selected elements

Example:
$ (“ . content”) . prepend (add me at the start’);

after(): This method inserts content after (outside) the selected element

Example:

$ (“.content”) . after (‘<p>add me after</p>’);

before(): As the name suggests, this method adds content before (outside) the selected element

Example:

$(".content").before('<p>add me before</p>');

Remove DOM Content: There are mainly two jQuery methods to remove elements and contents.

remove() : This method removes selected elements

Example:

$ (“#container-one”) . remove ( );

empty() : With this method we can remove child elements of selected elements

Example:

$ (“#container-two”) . empty ( );

20.2.2 jQuery CSS Styling

jQuery has many methods for CSS manipulation. Following four are the most important jQuery methods for
CSS manipulation.

addClass(): This method adds one or more classes to the selected elements

Example:

$ (“. content-1”) . addClass (‘blue’);

removeClass(): It removes one or more classes from the selected elements

Example:

$ (“ . content-2”) . removeClass(‘ red’ );

toggleClass(): With this method we can toggle between adding/removing classes from the selected
elements.

Example:
$ (“ . content-3”) . toggleClass (‘green’);

css(): We can set the style attributes for selected elements with this method

Example:

$ (“ . content-1”) . css (‘border’, ‘1px solid red’);

20.2.3 Handling Events


Events are actions of the website visitors that can be detected by your Web Application. Some of the
examples of the events are: a mouse click, web page loading, taking mouse over an element, submitting html
form, a keystroke on keyboard etc. When such events triggered, we can use jQuery methods to take some
action. In most of the previous examples, we have tracked the click event to manipulate DOM elements.

• Mouse Events: Here are some of the popular mouse events, click, dbclick, mouseenter and
mouseleave, hover
• Keyboard Events: Some of the important keyboard events are keypress, keydown and keyup
• Form Events: submit, change, focus, blur are important form events.
• Document/Window Events: Important document events includes load, ready, scroll

jQuery Event Syntax: The syntax for jQuery Event handling is pretty straightforward.

Example:

$ (“button”) . click (function ( ){


$(“p”) . hide( );
});

The click() method, attaches an event function to the selected html element (button in this case). The code
inside the function() gets executed only when the event happens, that is when the visitor clicks the button.
On happening of the button click event, all the <p> tags will hide. Here are some more examples of jQuery
event handling:

Mouse Double Click Event:

$ (“button”) . dbclick(function ( ){
$ (“p”) . hide ( );
});

Form Focus Event:

Example:

$ (“input”) . focus (function ( ) {


$(“p”) . css(“background-color”, “#cccccc”);
});
20.2 Check Your Progress

True or False

1. The val() method sets and gets the value of form field
2. append() method adds content at the beginning of the element

20.3 Summary

jQuery is a JavaScript Library developed by John Resig in 2006. With jQuery you can easily select and modify
DOM elements, handle events, add animation effects. It is light weight and cross browser supported. jQuery
syntax consists of two parts, selector and action to be performed. Methods like text() val() and html() are used
to get and set content in HTML DOM. jQuery can also be used to style the elements.

20.4 Check Your Progress Answers

20.1

1. True

20.2

1. True
2. False
Chapter 21

Latest Trends in JavaScript

21.0 Objectives

21.1 Introduction

21.1.1 Strict Mode

21.1.2 Regular Expression

21.1.3 Object Oriented JavaScript

21.1.4 Working with AJAX

21.1.5 ECMA Script

21.1.6 Server Side JavaScript: NODE.js

21.1.7 JSON

21.1.8 JavaScript Frameworks: Vue.js, Angular.js, React.js

21.2 Summary

21.3 Check Your Progress Answers

21.0 Objectives

After studying this chapter you will be able to understand

- how to use strict mode

- concepts like regular expression, object oriented JavaScript, Ajax

- distinction between ECMA script and JavaScript

- use of JavaScript as server side language

- what is JavaScript framework and introduction to popular framework

21.1 Introduction

JavaScript development is changing quickly, especially over the past few years. Lot of action, changes, and
new initiatives in front-end web development happened in recent years.

21.1.1 Strict Mode

JavaScript is a loosely typed (dynamic) scripting language. If you have worked with languages like Java or C#,
you must be familiar with the strictness of the language. For example, you expect the compiler to give an
error if you have used a variable before defining it. JavaScript allows similar strictness of the code using "use
strict" with ECMAScript 5 or later. You write "use strict" at the top of JavaScript code to activate strictness as
below.

“use strict”;

var x = 1; //valid in strict mode

y = 1; // invalid in strict mode

The strict mode in JavaScript does not allow you to do many things including: use of undefined variables, use
of reserved keywords, duplicate properties of an object, duplicate parameters of function, assign values to
read-only property etc.

21.1.2 Regular Expression

Regular expressions are patterns applied to match character combinations in strings. You can imagine regular
expressions as wildcards. You may be most likely familiar with wildcard notations such as *.txt to find all text
files in a file manager. In JavaScript, regular expressions are also objects. They are a powerful tool for
inspecting and processing strings. Properly understanding regular expressions will make you a more powerful
programmer.

21.1.3 Object Oriented JavaScript

Object Oriented Programming (OOP) refers to using self-contained parts of code to develop applications.
These self-contained parts of code are called as objects or classes. Building applications with objects enables
us to implement some valuable techniques, namely, Inheritance, Polymorphism and Encapsulation. JavaScript
began with simple one-liners embedded in HTML, but is now used in much more complex ways. JavaScript
developers leverage the object-oriented nature of the language to build scalable code architectures composed
of reusable parts.

21.1.4 Working with AJAX

Ajax stands for Asynchronous JavaScript and XML. It is not a programming language or a tool, but a
concept. Ajax is a client-side script that communicates to and from a server/database without the need for a
complete page refresh. In simple words Ajax is “the method of exchanging data with a server, and updating
parts of a web page – without reloading the entire page.” Now a days, Ajax uses JSON instead of XML to
transmit data between browser and server.

Benefits of Ajax:

• Update a web page without reloading the page


• Request data from a server - after the page has loaded
• Receive data from a server - after the page has loaded
• Send data to a server - in the background
21.1.5 ECMA Script

ECMAScript is the specification and JavaScript is based on it. By reading the ECMAScript specification, you
learn how to create a scripting language. By reading the JavaScript documentation, you learn how to use a
scripting language. ECMAScript 1, the first version of the JavaScript language standard, was released in June
1997. ECMAScript 6, the current version was released in 2015.

21.1.6 Server Side JavaScript: NODE.js

JavaScript is mainly a client side scripting language but with Node.js it can work as sever side language as well.
Node.js is a free open source server environment that runs on various platforms (Windows, Linux, Unix, Mac
OS X, etc.) and uses JavaScript on the server.

Node.js runs single-threaded, non-blocking, asynchronously programming, which is very memory efficient.
Node.js can generate dynamic page content. It can create, open, read, write, delete, and close files on the
server. It can also collect form data and add, delete, modify data in your database. You can build complete
web application with node.js

21.1.7 JSON

When exchanging data between a browser and a server, the data can only be text. JSON, or JavaScript Object
Notation, is a minimal, human readable format for structuring data. It is used primarily to transmit data
between a server and web application, as an alternative to XML. The two primary parts that make up JSON
are keys and values. Together they make a key/value pair.

• Key: A key is always a string enclosed in quotation marks.


• Value: A value can be a string, number, boolean expression, array, or object.

Example:

“age" : “21”

Where "age" is key and "21" is value.

21.1.8 JavaScript Frameworks: Vue.js, Angular.js, React.js

A JavaScript framework is something from which you can build web application. A framework provides some
rules and guidelines. Using those rules and guidelines help you in building awesome web application rapidly.

The advantages of using JavaScript frameworks:

• Efficiency: Projects that used to take months and thousands of lines of code now can be achieved
much faster with well-structured pre-built patterns and functions.
• Safety: Top JavaScript frameworks have firm security arrangements and are supported by large
communities where members and users also act as testers.
• Cost: Most frameworks are open source and free. Since they help programmers to build custom
solutions faster, the ultimate price for web application will be lower.
Some of the most popular JavaScript Frameworks are:

Angular.js

Angular.js it is one of the most beloved and used JavaScript frameworks for building single page applications.
It is available as an open source solution and is supported by Google. Angular JS is highly preferred for
hybrid mobile application development. Featured with components like overlays, sidebars, switches and
absolute positioned navigation bars, this framework incorporates dynamic functionality to the application.

React.js

React.js was created by the team of Facebook developers and came out in 2013. Being pretty new in
comparison with other JavaScript frameworks it confidently wins its niche. If you like the user interface of
Facebook and Instagram then you might like React.js too. This very framework is behind the front-end
scenes of the two social giants. There are other companies that benefit from using it: Atlassian, BBC,
Coursera, Dropbox, Flipboard, Netflix, Paypal, WhatsApp.

Vue.js

Introduced in 2016, Vue has a low learning curve. The framework delivers two-way data binding, server-side
rendering, Vue-CLI and optional JSX support. It is one the fastest emerging frameworks till date and is a
preferable choice for quick cross-platform solutions.

There are many other popular JavaScript Frameworks like Polymer, Aurelia.js, Embre.js and Backbone.js but
the above three are currently the most popular.

21.1 Check Your Progress

True or False

1. Ajax stands for Asynchronous JavaScript and XML.


2. ECMA script and JavaScript are same.
3. Strict mode brings in strictness of the code in JavaScript.

21.2 Summary

Although the core of JavaScript has remained the same, JavaScript has changed a lot in recent time. Now it
can be used as server side language. The ECMAScript 5 and later has introduced some new features like strict
mode in JavaScript. JSON has made life easier for developers. The most exciting thing happened to
JavaScript is emergence of numerous JavaScript Frameworks like Angular, React and Vue.

21.3 Check Your Progress Answers

21.1

1. True
2. False
3. True
Chapter 22

Web Design Latest Trends

22.0 Objectives

22.1 Introduction

22.1.1 Git and Github: Version Control

22.1.2 Gulp: Automated Task Runner

22.1.3 Understanding SASS

22.2 Summary

22.3 Check Your Progress Answers

22.0 Objectives

After studying this chapter you will be able to understand

- what is version control system and some of the important concepts of git

- what is gulp

- how to use SASS

22.1 Introduction
A version control system is an application that allows you monitor the history and attribution of your project
files, and which helps the developers in the team to work together. Present day version control systems help
them work together, in a non-blocking way, by providing each developer his or her own sandbox, avoiding
their work in progress from conflicting, and all the while offering a mechanism to merge changes and
synchronize work.

22.1.1 Git and Github: Version Control


Git is a version control system. It is free and open source. For example, if you have a file on which you’ve
been doing work on and reworking for a long time, all the versions of it are saved in Git, and you can quickly
get back to every version.

Benefits of Using Git Version Control System:


• It is free and open source.
• You have access to all versions of all files in Git repository at any time
• Multiple developers can work on one project at the same time without interfering with each other,
and without fear of losing any changes made by a colleague.
• The chances of losing data are very rare when there are multiple copies of it.

Important Concepts of Git:


• Repositories: A repository is a folder inside which you are going to store every piece of your code.
• To fork a project: Copying someone’s repository into your account is called forking. You can do
your own work in your newly forked repository without affecting the original files. This is an
amazing feature that significantly encourages the further development of programs and other
projects.
• Branches: Branches are used to create another line of development. Within a repository you have
branches, which are effectively forks (clones) within your own repository. Usually, a branch is created
to work on a new feature. Once the feature is completed, it is merged back with the master branch
and the branch is deleted.
• Pull: You’ve forked a repository, made a great revision to the project, and want it to be recognized
by the original developers—maybe even included in the official project/repository. To do this you
can do so by creating a pull request.
• Push: Push operation copies changes from a local repository instance to a remote one (forked
earlier).
• Commit: In Git, a commit is used to record changes to a repository.
• Merges: It is combining of multiple branches in one.
• Revision: Revision represents the version of the source code.

Github:
GitHub.com is the leading code-hosting platform with virtually millions of open source projects having their
code hosted on it. In conjunction with Git, it supplies the means for a productive development workflow and
is the preferred git tool among developers.

22.1.2 Gulp: Automated Task Runner


Gulp solves the problem of repetition. Gulp is a toolkit for automating painful or time-consuming tasks in
your development workflow, so you can stop doing repetitive tasks and build something quickly. It is a one of
the most popular JavaScript build systems available today.

Benefits of Using Gulp:


• Bundling and minifying libraries and stylesheets.
• Refreshing your browser when you save a file.
• Quickly running unit tests
• Running code analysis
• Less/Sass to CSS compilation

22.1.3 Understanding SASS


CSS on its own can be fun, but stylesheets are getting larger, more complex, and harder to maintain. This is
where a preprocessor can help. SASS (Syntactically Awesome Style Sheets) lets you use features that don't
exist in CSS yet like variables, nesting, mixins, inheritance and other nifty goodies that make writing CSS fun
again.

The aim is to make the coding process simpler and more efficient. A CSS preprocessor is a scripting language
that extends CSS by allowing developers to write code in one language and then compile it into CSS. Sass is
perhaps the most popular preprocessor around, but other common alternatives are Less and Stylus.

Sass includes two syntax options:

• .scss (Sassy CSS): Uses the .scss file extension and is fully compliant with CSS syntax
• .sass: Uses .sass file extension and indentation rather than brackets; it is not fully compliant with
CSS syntax, but it's quicker to write

Benefits of Using SASS:

• SASS makes writing your CSS quicker


• SASS allows us to define variables that are reusable throughout our entire project
• With the help of @extend attribute you can avoid duplication of code

Important Concepts:

Variables:
Think of variables as a way to store information that you want to reuse throughout your stylesheet. You can
store things like colors, font stacks, or any CSS value you think you'll want to reuse.

Example:

$primary-color: #333;

body{

color: $primary-color;

Nesting:
SASS lets you nest your CSS selectors in a way that follows the same visual hierarchy that your HTML code
follows.

Example:

nav{

ul{

margin: 0;
padding: 0;

padding: 0;

list-style: none;

Import:
CSS has an import option that lets you split your CSS into smaller, more maintainable portions. The only
drawback is that each time you use @import in CSS it creates another HTTP request. Sass builds on top of
the current CSS @import but instead of requiring an HTTP request, Sass will take the file that you want to
import and combine it with the file you're importing into so you can serve a single CSS file to the web
browser.

Mixins:
Some things in CSS are a bit tedious to write, especially with CSS3 and the many vendor prefixes that exist. A
mixin lets you make groups of CSS declarations that you want to reuse throughout your site. You can even
pass in values to make your mixin more flexible. A good use of a mixin is for vendor prefixes. Here's an
example for border-radius.

Example:

@mixin my-border-radious($radius){

-webkit-border-radious: $radiou;

-moz-border-radious: $radious;

-ms-border-radius: $radius;

border-radius: $radius;

.box{

@include my-border-radious(10px);

22.1 Check Your Progress

True or False
1. Git is a version control system
2. Gulp solves the problem of repetition
3. SASS lets you use features that don't exist in CSS yet.

22.2 Summary

Although the core of JavaScript has remained the same, JavaScript has changed a lot in recent time. Now it
can be used as server side language. The ECMAScript 5 and later has introduced some new features like strict
mode in JavaScript. JSON has made life easier for developers. The most exciting thing happened to
JavaScript is emergence of numerous JavaScript Frameworks like Angular, React and Vue.

22.3 Check Your Progress Answers

22.1

1. True
2. True
3. True
Questions Bank: Questions for Self Study

Chapter 1:

1. What is WWW?
2. Explain the term internet?
3. Differentiate between WWW and internet.
4. What is URL?
5. Write a short note on Operating System.
6. What is HTML?
7. Describe the three layers of Web.
8. Discuss two sided tags and one sided (empty) tags with example.

Chapter: 2

1. Write a short note on document type declaration


2. Explain the <html>, <head> and <body> tags
3. Write a 'Hello World' HTML program.
4. Describe the process of adding CSS file and JavaScript file to HTML file.

Chapter: 3

1. Discuss heading tags.


2. Discuss three types of lists.
3. What is the difference between absolute path and relative path?
4. Explain how to link a telephone number with example.
5. Discuss important concepts of displaying data with table
6. Write a short note on HTML comments

Chapter: 4

• Write a short note on creation of basic form and its elements


• Discuss form tag attributes.
• List out various types of input text boxes
• What is placeholder text
• Discuss checkbox, radio and select option dropdown elements

Chapter: 5

• What is Semantic markup?


• List out various semantic elements.
• Discuss how section, article, aside and address tags should be used.
• Explain how Audio and Video elements work with example

Chapter: 6

• What is CSS?
• Describe the 3 methods of adding CSS to HTML.
• Discuss different units of measurements.
• Differentiate between Block Level and Inline Level element.

Chapter: 7

• Discuss element selector, id selector and class selector.


• Differentiate between descendant selector, child selector and sibling selector
• Write a short note on Specificity Calculator.

Chapter: 8

• Describe the process of adding local and external fonts.


• Explain with example how to add color to text.
• Discuss properties like font-weight, font-style, text-transform, text-align and text-decoration
• Discuss letter-spacing and word-spacing property.
• List out various paragraph styles

Chapter: 9

• What is CSS box model?


• Write a short note on width and height properties. Also explain minimum / maximum width and
height.
• List out various properties related to the padding property.
• Discuss background CSS property.

Chapter: 10

• Discuss the position property and its options.


• What is float and clear float?
• What is the difference between the display and visibility property?
• Write a short note on Flexbox.

Chapter: 11

• What is responsive web design?


• What is the difference between desktop first and mobile first.
• Write a short note on media queries.

Chapter: 12

• Explain the term box shadow.


• Write a short note on Gradient. List out various gradient types.
• Describe the transform property and its options.
• Discuss transition effect.

Chapter: 13
• What is bootstrap?
• Explain the bootstrap grid system
• List out some text related bootstrap classes.
• List out image related bootstrap classes.

Chapter: 14

• What is JavaScript?
• Differentiate between Java and JavaScript.
• Write a short note on Client Server Architecture
• Describe how to add JavaScript to HTML.

Chapter: 15

• What is variable?
• List out various data types in JavaScript.
• Write a short note on concatenating string
• Differentiate between Null and Undefined
• Explain the term array

Chapter: 16

• What is conditional statement?


• List out various conditional statements in JavaScript.
• Write a short note on switch statement
• Discuss while loop and for loop

Chapter: 17

• What is a function?
• Discuss the concept passing data to function
• What is return statement?
• Write a short note on function scope.

Chapter: 18

• What is DOM?
• List out various methods of finding elements on page.
• Discuss finding parent element, children and sibling of element in JS

Chapter: 19

• List out various window events.


• List out various mouse events.

Chapter: 20
• What is jQuery? What can you do with it?
• Write short note on jQuery factory function and document.ready() method
• Discuss jQuery syntax
• List out 3 jQuery DOM manipulation methods
• Explain how jQuery can be used to style elements
• Discuss how jQuery handle events

Chapter: 21

• What is strict mode?


• Write a short note on Object Oriented JavaScript
• Explain the term AJAX
• List out various JavaScript Frameworks

Chapter 22:

• What is Git and Github?


• Write a short note on Gulp.
• Explain the term SASS
• List out various concepts of SASS
Suggested Readings:

HTML 5:

HTML and CSS: Design and Build Websites by Jon Duckett

HTML5: The Missing Manual by Matthew MacDonald

HTML5 In Easy Steps by Mike McGrath

HTML5 Pocket Reference by Jennifer Niederst Robbins

HTML5: Up and Running by Mark Pilgrim

HTML5 Foundations by Matt West

CSS:

CSS: The Definitive Guide By Eric A. Meyer

The Book of CSS3 By Peter Gasston

CSS: The Missing Manual By David Sawyer McFarland

CSS3 Foundations By Ian Lunn

CSS Pocket Reference By Eric A. Meyer

Bootstrap:

Learning Bootstrap 4 By Matt Lambert

Introducing Bootstrap 4 BY Jörg Krause

Bootstrap 4 Cookbook By Ajdin Imsirovic

JavasScript:

JavaScript: The Definitive Guide By David Flanagan

JavaScript & jQuery: The Missing Manual By David Sawyer McFarland

Professional JavaScript for Web Developers By Nicholas C. Zakas

JavaScript Pocket Reference By David Flanagan

JavaScript and JQuery: Interactive Front-End Web Development By Jon Duckett

jQuery:

jQuery Pocket Reference By David Flanagan

JavaScript & jQuery: The Missing Manual By David Sawyer McFarland


Learning jQuery By Jonathan Chaffer and Karl Swedberg

jQuery Cookbook By Cody Lindley

Git:

Pro Git By Scott Chacon and Ben Straub

Version Control with Git By Jon Loeliger and Matthew McCullough

Gulp:

Getting Started with Gulp By Travis Maynard

SASS:

Sass and Compass for Designers By Ben Frain

Jump Start Sass By Hugo Giraudel and Miriam Suzanne

You might also like