0% found this document useful (0 votes)
425 views103 pages

Chapter (1) Fundamental of Web Technology

The document provides an overview of fundamental web technologies and concepts. It defines the Internet and distinguishes it from the World Wide Web (WWW). It describes how the WWW allows users to access multimedia documents through browsers. It also defines key concepts like clients and servers, domains and URLs, protocols, and types of website content. Static websites contain pages that are delivered exactly as stored, while dynamic websites generate pages tailored to each user.

Uploaded by

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

Chapter (1) Fundamental of Web Technology

The document provides an overview of fundamental web technologies and concepts. It defines the Internet and distinguishes it from the World Wide Web (WWW). It describes how the WWW allows users to access multimedia documents through browsers. It also defines key concepts like clients and servers, domains and URLs, protocols, and types of website content. Static websites contain pages that are delivered exactly as stored, while dynamic websites generate pages tailored to each user.

Uploaded by

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

Chapter (1)

Fundamental of Web Technology


1. To understand the concept of Web technologies and its Architecture

What is Internet?

1.1.Understand that the Internet supports a range of services such as the World Wide Web (WWW), File
Transfer(email, instant messaging (IM))

The Internet or "the network of networks" is a public network that connects computers and computer
networks around the world through a common protocol (IP). All connected computers and networks
mutually exchange information and use various services. Hence, the Internet is not solely the WWW, or
pages and content available from a browser. In fact, the WWW is just one of the services that the Internet
offers to its users although it is the most commonly used service. Other available services:

World Wide Web (WWW)


 The World Wide Web allows computer users to locate and view multimedia-based documents (i.e.,
documents with text, graphics, animations, audios or videos) on almost any subject.
 Even though the Internet was developed more than three decades ago, the introduction of the World
Wide Web is a relatively recent event. In 1990, Tim Berners-Lee of CERN (the European Laboratory for
Particle Physics) developed the World Wide Web and several communication protocols that form the
backbone of the Web.
 The Internet and the World Wide Web surely will be listed among the most important and profound
creations of humankind.
 In the past, most computer applications executed on “stand-alone” computers (i.e., computers that
were not connected to one another).
 The W3C is also a standardization organization.
 Web technologies standardized by the W3C are called Recommendations. W3C Recommendations
include the Extensible Hyper-Text Markup Language (XHTML), Cascading Style Sheets (CSS), Hypertext
Markup Language (HTML; now considered a “legacy” technology) and the Extensible Markup Language
(XML).
 The W3C homepage (www.w3.org) provides extensive resources on Internet and Web technologies.

File transfer - the file transfer from one computer to another.

 E-mail (electronic mail) – it is the oldest Internet service, and it enables the exchange of digital
messages between two or more people.
 Instant messaging (IM) – it enables the exchange of electronic messages between two or more people
in real time. Such as chat rooms (Gtalk, MSN, Skype, etc.) that also support nowadays video/ audio/
photo communication exchange.

1.2. Understand the term client/server. Understand the functionality and relationship between the
browser and the web server

The Internet is probably the best-known example of a client/ server relationship. The difference between a
client and a server is big. Here we have two computers/ programs where the client sends requests to a
server, and the server processes requests and returns the results to the client. A server is typically a remote
computer not visible to the user.

1
 Web server: is the computer/ server whose entire content is visible on a website in a web browser.
Web servers are constantly connected to the Internet. We access them through URL. Therefore, if we
enter, for example, www.google.com in a web browser, we are accessing the Google server.
 Web browser: enables browsing through websites. Its mechanisms display the content, retrieved from
the server, in a correct and understandable way. As such it is an intermediary between the user and
the server. (e.g. Google Chrome, Firefox, Internet Explorer, etc.)

1.3. Understand the terms domain, Uniform Resource Locator (URL), hyperlink, web hosting, search
engine.

The domain is a unique name on the Internet. We might say that what in real life the ID is for a human, this
is what the domain name is for a web page.

URL (Uniform Resource Locator) is another term for a web address. A URL has three parts:

 protocol name (e.g., HTTP)


 domain name/ hostname (servers address that a user wants to connect with), for example,
www.google.com
 file name is optional, implies the access to a file/directory into the principal webpage. It is separated by
slash. Therefore, when we enter http://www.google.com in the address bar in our web browser; the
browser is instructed to connect to a server with the domain www.google.com by using the HTTP
protocol.
 Hyperlinks are separately marked words, images and other elements on a web page that represent a
direct link to additional information. Most often we open other web pages when we click on hyperlinks.

1.4. Understand the use of primary protocols: Transmission Control Protocol/ Internet Protocol (TCP/lP),
Hypertext Transfer Protocol (HTTP), File Transfer Protocol (FTP)

 TCP/IP protocol:
TCP / IP: This protocol is the main protocol for Internet communication. It defines the rules that
computers need to follow to communicate with other computers via a network. TCP is responsible for
separating messages. They are then sending across the network in smaller packets (packages). They
reassemble again at the destination to present the initially sent message.
 HTTP (Hypertext Transfer protocol):
HTTP is a network protocol that ensures the exchange of almost all types of resources on the web. With
resources, we mean files, pages, images, search results, etc. It is basically, the web browsers language to
send requests to the server. There is also the HTTPS version, which is a secure and encrypted version for
HTTP communications.
 FTP (File Transfer Protocol):
FTP is used to load (upload) or retrieve (download) files between the client and server communication,
or between two computers on the Internet. In other words, this protocol is responsible for file transfer
on the Internet.

Web Contents

 Web content is the textual, visual or aural content that is encountered as part of the user experience on
websites.
 It may include, among other things: text, images, sounds, videos and animations.

2
1.5. HTML web content

 Even though we may embed various protocols within web pages, the "web page" composed of "html"
(or some variation) content is still the dominant way whereby we share content. And while there are
many web pages with localized proprietary structure (most usually, business websites), many millions of
websites abound that are structured according to a common core idea.
 A web search engine is designed to search for information on the World Wide Web.
 The search results are generally presented in a list of results and are often called hits.
 The information may consist of web pages, images, information and other types of files. Some search
engines also mine data available in databases or open directories.
 Unlike Web directories, which are maintained by human editors, search engines operate algorithmically
or are a mixture of algorithmic and human input.

Types of Website Content

 Static Web Site


 Dynamic Web Site

Static Web Site

 A static web page (sometimes called a flat page) is a web page that is delivered to the user exactly as
stored.
 Dynamic web pages which are generated by a web application
 Consequently a static web page displays the same information for all users, from all contexts, subject to
modern capabilities of a web server to negotiate content-type or language of the document where such
versions are available and the server is configured to do so.
 Static web pages are often HTML documents stored as files in the file system and made available by the
web server over HTTP.
 However, loose interpretations of the term could include web pages stored in a database, and could
even include pages formatted using a template and served through an application server, as long as the
page served is unchanging and presented essentially as stored.
 Static Web pages are very simple in layout and informative in context. Creation of static website content
requires great level of technical expertise and if a site owner is intended to create static.
 Web pages, they must be very clear with their ideas of creating such pages since they need to hire a web
designer.

Advantages

 No programming skills are required to create a static page.


 Inherently publicly cacheable (i.e. a cached copy can be shown to anyone).
 No particular hosting requirements are necessary.
 Can be viewed directly by a web browser without needing a web server or application server, for
example directly from a CDROM or USB Drive.

Disadvantages

 Any personalization or interactivity has to run client-side (ie. In the browser), which is restricting.
 Maintaining large numbers of static pages as files can be impractical without automated tools

3
Application areas of Static Website:

 Need of Static web pages arise in the following cases


 Changes to web content is infrequent
 List of products / services offered is limited Simple e-mail based ordering system should suffice
 No advanced online ordering facility is required
 Features like order tracking, verifying availability of stock, online credit card transactions, are not needed
 Web site not required to be connected to back-end system.

1.6.Dynamic Web Sites

 A dynamic web page is a kind of web page that has been prepared with fresh information (content
and/or layout), for each individual viewing.
 It is not static because it changes with the time (ex. a news content), the user (ex. preferences in a login
session), the user interaction (ex. web page game), the context (parametric customization), or any
combination of the foregoing.

Two types of dynamic web sites

 Client-side scripting and content creation


 Server-side scripting and content creation

Client-side scripting and content creation

 Client-side scripting and content creation Using client-side scripting to change interface behaviors within
a specific web page, in response to mouse or keyboard actions or at specified timing events. In this case
the dynamic behavior occurs within the presentation.
 Such web pages use presentation technology called rich interfaced pages. Client-side scripting languages
like JavaScript or ActionScript, used for Dynamic HTML (DHTML) and Flash technologies respectively, are
frequently used to orchestrate media types (sound, animations, changing text, etc.) of the presentation.
 The scripting also allows use of remote scripting, a technique by which the DHTML page requests
additional information from a server, using a hidden Frame, XMLHttpRequests, or a Web service.
 The Client-side content is generated on the user's computer.
 The web browser retrieves a page from the server, then processes the code embedded in the page
(often written in JavaScript) and displays the retrieved page's content to the user.
 The innerHTML property (or write command) can illustrate the client-side dynamic page generation: two
distinct pages, A and B, can be regenerated as document.
 innerHTML = A and document. innerHTML = B; or "on load dynamic" by document.write(A) and
document.write(B)

Server-side scripting and content creation

 Using server-side scripting to change the supplied page source between pages, adjusting the sequence
or reload of the web pages or web content supplied to the browser.
 Server responses may be determined by such conditions as data in a posted HTML form, parameters in
the URL, the type of browser being used, the passage of time, or a database or server state.
 Such web pages are often created with the help of server side languages such as PHP, Perl, ASP,
ASP.NET, JSP, ColdFusion and other languages.

4
 These server-side languages typically use the Common Gateway Interface (CGI) to produce dynamic web
pages. These kinds of pages can also use, on the client-side, the first kind (DHTML, etc.).

An application area of Dynamic Website Dynamic web page is required when following necessities arise:

 Need to change main pages more frequently to encourage clients to return to site.
 Long list of products / services offered that are also subject to up gradation
 Introducing sales promotion schemes from time to time
 Need for more sophisticated ordering system with a wide variety of functions
 Tracking and offering personalized services to clients.
 Facility to connect Web site to the existing back-end system

The fundamental difference between a static Website and a dynamic Website is a static website is no more
than an information sheet spelling out the products and services while a dynamic website has wider
functions like engaging and gradually leading the client to online ordering. But both static web site design
and dynamic websites design can be designed for search engine optimization. If the purpose is only to
furnish information, then a static website should suffice. Dynamic website is absolutely necessary for e-
commerce and online ordering.

1.7. Web Technologies


 HTML, which stands for Hypertext Markup Language, is the predominant markup language for web
pages. It is written in the form of HTML elements consisting of "tags" surrounded by angle brackets
within the web page content.
 It allows images and objects to be embedded and can be used to create interactive forms. It provides a
means to create structured documents by denoting structural semantics for text such as headings,
paragraphs, lists, links, quotes and other items. It can embed scripts in languages such as JavaScript
which affect the behavior of HTML web pages.
 HTML can also be used to include Cascading Style Sheets (CSS) to define the appearance and layout of
text and other material. The W3C, maintainer of both HTML and CSS standards, encourages the use of
CSS over explicit presentational markup.

Introduction to Web Servers

 A web Server is a program that automatically downloads pages from the Web
 An application server works with a Web server to handle requests for dynamic content, such as servlets,
from Web applications. A Web server uses a Web server plug-ins to establish and maintain persistent
HTTP and HTTPS connections with an application server.
 The web server software offers access to documents stored on the server.
 Clients can browse the documents in a web browser.
 The documents can be for example static Hypertext Markup Language (HTML) files, image files or
various script files, such as Common Gateway Interface (CGI), Javascript or Perl files. The communication
between clients and server is based on the Hypertext Transfer Protocol (HTTP)
 We have the Following Web Servers

Apache1.1 2.WAMP 3.XAMPP

5
Chapter (2)

Fundamental of Design

An Introduction to the Basics

2.1 What Is Web Design?

As websites and online resources become more and more a part of our everyday lives, there is an increased
demand for web design skills — but what exactly is "web design?" Simply put, web design is the planning
and creation of websites. This includes a number of separate skills that all fall under the umbrella of web
design. Some examples of these skills are information architecture, user interface, site structure, navigation,
layout, colors, fonts and overall imagery. All of these skills are combined with the principles of design to
create a website that meets the goals of the company or individual from whom that site is being created.
This article will take a look at the basics of website design and the various disciplines or skills that are a part
of this industry.

Web Design Has Many Different Roles

When you work as a web designer, you may be tasked with creating (or working on) entire sites or just
individual pages and there is a lot to learn to be a well-rounded designer, including the following:

 HTML: This is the structure of web pages, creating the foundation of all websites.
 CSS: This is how web pages are visually styled. CSS (Cascading Style Sheets) handles the entire look of
sites, including layout, typography, colors, and more.
 JavaScript: This governs certain behaviors on websites and can be used for a variety of interactions
and features.
 CGI programming: CGI and the next few entries (PHP, ASP, etc.) are all different flavors of
programming languages. Many sites do not require any of these languages, but sites that are more
feature-rich will certainly need to be coded using some of these languages.
 PHP, ASP, ColdFusion scripting.
 XML.
 Information architecture: The way a site's content and navigation is structured and presented helps
make for a successful site that is easy and intuitive to use.
 SEO: Search engine optimization ensures that websites are attractive to Google and other search
engines and that people looking for the products, services, or information features on that site can find it
once they look for it online.

6
 Server management: All websites need to be hosted. The management of the servers that host
those sites is an important web design skill.
 Web strategy and marketing: Having a website is not enough. Those sites will also need to be
marketed with an ongoing digital strategy.
 E-commerce and conversions.
 Design: Creating the visual look and feel of websites has always been an important aspect of the
industry.
 Speed: A successful site is one that loads quickly on a wide variety of devices, regardless of a visitors
connection speed. Being able to tune the performance of sites is a very valuable skill.
 Content: People come to websites for the content that those sites contain. Being able to create that
content is a critically important component in the world of website design.

UI/UX Designer responsibilities include gathering user requirements, designing graphic elements and
building navigation components.

Responsibilities

 Gather and evaluate user requirements in collaboration with product managers and engineers
 Illustrate design ideas using storyboards, process flows and sitemaps
 Design graphic user interface elements, like menus, tabs and widgets
 Build page navigation buttons and search fields
 Develop UI mockups and prototypes that clearly illustrate how sites function and look like
 Create original graphic designs (e.g. images, sketches and tables)
 Prepare and present rough drafts to internal teams and key stakeholders
 Identify and troubleshoot UX problems (e.g. responsiveness)
 Conduct layout adjustments based on user feedback
 Adhere to style standards on fonts, colors and images

7
Chapter (3)

Fundamental of UI DESIGN

1. To understand the Essentials of Web Application Development.


2. To understand and practice web page designing techniques.

Introduction to HTML

3.1. Basics of HTML

Understand the term Hypertext Markup Language (HTML). HTML is a presentational language that we use
for the purpose of developing web pages.

It is a descriptive language used to describe a document's layout, image position, font size, font color, etc.

TML is not a programming language, and it cannot complete tasks regarding programming (arithmetic or the
use of variables), not even the simplest program logic.

Objectives: By the end of this workshop, you will be able to:

 Use a text editor to author an HTML document.


 Be able to use basic tags to denote paragraphs, emphasis or special type.
 Create hyperlinks to other documents.
 Create an email link.
 Add images to your document.
 Use a table for layout.
 Apply colors to your HTML document.

Prerequisites: You will need a text editor, such as Notepad and an Internet browser, such as Internet
Explorer or Netscape.

What is Notepad and where do I get it?

A: Notepad is the default Windows text editor. On most Windows systems, click your Start button
and choose Programs then Accessories. It should be a little blue notebook.

Mac Users: SimpleText is the default text editor on the Mac. In OSX use TextEdit and change the
following preferences: Select (in the preferences window) Plain text instead of Rich text and then
select Ignore rich text commands in HTML files. This is very important because if you don't do this
HTML codes probably won't work.

One thing you should avoid using is a word processor (like Microsoft Word) for authoring your HTML
documents.

What is an html File?

HTML is a format that tells a computer how to display a web page. The documents themselves are plain text
files with special "tags" or codes that a web browser uses to interpret and display information on your
computer screen.

8
 HTML stands for Hyper Text Markup Language
 An HTML file is a text file containing small markup tags
 The markup tags tell the Web browser how to display the page
 An HTML file must have an htm or html file extension

Try It?

Open your text editor and type the following text:

<html>
<head> <title>My First Webpage</title>
</head>
<body> This is my first homepage. <b>This text is bold</b>
</body>
</html>

Save the file as mypage.html. Start your Internet browser. Select Open (or Open Page) in the File menu of
your browser. A dialog box will appear. Select Browse (or Choose File) and locate the html file you just
created - mypage.html - select it and click Open. Now you should see an address in the dialog box, for
example C:\MyDocuments\mypage.html. Click OK, and the browser will display the page.

How to view HTML Source

A good way to learn HTML is to look at how other people have coded their html pages. To find out, simply
click on the View option in your browsers toolbar and select Source or Page Source. This will open a window
that shows you the actual HTML of the page. Go ahead and view the source html for this page.

3.2. HTML Tags & Elements

 HTML tags are used to mark-up HTML elements


 HTML tags are surrounded by the two characters < and >
 The surrounding characters are called angle brackets
 HTML tags normally come in pairs like <b> and </b>
 The first tag in a pair is the start tag, the second tag is the end tag
 The text between the start and end tags is the element content
 HTML tags are not case sensitive, <b> means the same as <B>

Logical vs. Physical Tags

In HTML there are both logical tags and physical tags.

Logical tags are designed to describe (to the browser) the enclosed text's meaning. An example of a logical
tag is the <strong> </strong> tag. By default all browsers make the text appear bold when in between the
<strong> and </strong> tags.

Physical tags on the other hand provide specific instructions on how to display the text they enclose.
Examples of physical tags include:

 <b>: Makes the text bold.


 <big>: Makes the text usually one size bigger than what's around it.
 <i>: Makes text italic.

9
Physical tags were invented to add style to HTML pages because style sheets were not around, though the
original intention of HTML was to not have physical tags. Rather than use physical tags to style your HTML
pages, you should use style sheets.

HTML Elements

<html>
<head> <title>My First Webpage</title>
</head>
<body> This is my first homepage. <b>This text is bold</b>
</body>
</html>

This is an HTML element:

<b>This text is bold</b>


The HTML element begins with a start tag:<b>

The content of the HTML element is:

This text is bold The HTML element ends with an end tag: </b>
The purpose of the <b> tag is to define an HTML element that should be displayed as bold.

This is also an HTML element:

<body>
This is my first homepage. <b>This text is bold</b>
</body>
This HTML element starts with the start tag <body>, and ends with the end tag </body>. The purpose of the
<body> tag is to define the HTML element that contains the body of the HTML document.

Nested Tags
You may have noticed in the example above, the <body> tag also contains other tags, like the <b> tab. When
you enclose an element in with multiple tags, the last tag opened should be the first tag closed.
For example:

<p><b><em>This is NOT the proper way to close nested tags.</p></em></b>

<p><b><em>This is the proper way to close nested tags. </em></b></p>

Tag Attributes

Tags can have attributes. Attributes can provide additional information about the HTML elements on your
page. The <tag> tells the browser to do something, while the attribute tells the browser how to do it.

For instance, if we add the bgcolor attribute, we can tell the browser that the background color of your page
should be blue, like this: <body bgcolor="blue">.

This tag defines an HTML table: <table>. With an added border attribute, you can tell the browser that the
table should have no borders: <table border="0">.

10
Attributes always come in name/value pairs like this: name="value". Attributes are always added to the start
tag of an HTML element and the value is surrounded by quotes.

Quote Styles, "red" or 'red'?

Attribute values should always be enclosed in quotes. Double style quotes are the most common, but single
style quotes are also allowed. In some rare situations, like when the attribute value itself contains quotes, it
is necessary to use single quotes:

name='George "machine Gun" Kelly'

3.2.1. Using Heading Tags

The most important tags in HTML are tags that define headings, paragraphs and line breaks.

Headings

Headings are defined with the <h1> to <h6> tags. <h1> defines the largest heading while <h6> defines the
smallest.
<h1>This is a heading</h1>
<h2>This is a heading</h2>

<h3>This is a heading</h3>

<h4>This is a heading</h4>

<h5>This is a heading</h5>

<h6> This is a heading</h6>

HTML automatically adds an extra blank line before and after a heading. A useful heading attribute is align.

<h5 align="left">I can align headings </h5>


<h5 align="center">This is a centered heading </h5>
<h5 align="right">This is a heading aligned to the right </h5>

3.3. Paragraphs

Paragraphs are defined with the <p> tag. Think of a paragraph as a block of text. You can use the align
attribute with a paragraph tag as well.

<p align="left">This is a paragraph</p>

<p align="center">this is another paragraph</p>

11
3.4. Line Breaks

The <br> tag is used when you want to start a new line, but don't want to start a new paragraph. The <br>
tag forces a line break wherever you place it. It is similar to single spacing in a document.

The <br> tag has no closing tag.

3.5. Horizontal Rule

The <hr> element is used for horizontal rules that act as dividers between sections, like this:

The horizontal rule does not have a closing tag. It takes attributes such as align and width. For instance:

3.6. Comments in HTML

The comment tag is used to insert a comment in the HTML source code. A comment can be placed anywhere
in the document and the browser will ignore everything inside the brackets. You can use comments to write
notes to yourself, or write a helpful message to someone looking at your source code.

Notice you don't see the text between the tags <!-- and -->. If you look at the source code, you would see the
comment. To view the source code for this page, in your browser window, select View and then select
Source.

HTML automatically adds an extra blank line before and after some elements, like before and after a
paragraph, and before and after a heading. If you want to insert blank lines into your document, use the
<br> tag.

Try It Out!

Open your text editor and type the following text:

<html>
<head> <title>My First Webpage</title> </head>
<body> <h1 align="center">My First Webpage</h1>
<p>Welcome to my first web page. I am writing this page using a text editor and plain old html.</p>
<p>By learning html, I'll be able to create web pages like a pro....<br> which I am of course.</p>
</body>
</html>
12
3.7. Other HTML Tags

As mentioned before, there are logical styles that describe what the text should be and physical styles which
actually provide physical formatting. It is recommended to use the logical tags and use style sheets to style
the text in those tags.

Logical Tags Physical Tags

3.8. Blockquote

The following paragraph uses the <blockquote> tag. In the previous sentence, the blockquote tag is enclosed
in the <samp> Sample tag.

Although most browsers render blockquoted text by indenting it, that's not specifically what it's designed to
do. It's conceivable that some future browser may render blockquoted text in some other way. However, for
the time being, it is perfectly safe to indent blocks of text with the <blockquote>.

When you hold your mouse pointer over the WWW, text in the title attribute will appear in.

3.9. HTML Character Entities

Some characters have a special meaning in HTML, like the less than sign (<) that defines the start of an HTML
tag. If we want the browser to actually display these characters we must insert character entities in place of
the actual characters themselves.

13
The Most Common Character Entities:

3.10. Non-breaking Space

The most common character entity in HTML is the non-breaking space &nbsp;. Normally HTML will truncate
spaces in your text. If you add 10 spaces in your text, HTML will remove 9 of them. To add spaces to your
text, use the &nbsp; character entity.

Note: Entities are case sensitive.

3.11. HTML Fonts

Font size is range from 1 to 7. If you don’t set the font size, web browser will displayed it at 3. To change font
size, you need <font> tag and size=”n” where n=1-7

Attribute: size=”value” face=”Font name” color=”color name or color code”


Eg: <FONT size=”4” face=”Arial” color=”green:>This font is Arial.</FONT>

The <font> tag in HTML is deprecated. The World Wide Web Consortium (W3C) has removed the <font> tag
from its recommendations. In future versions of HTML, style sheets (CSS) will be used to define the layout
and display properties of HTML elements.
The <font> Tag Should NOT be used.

3.12. HTML Backgrounds

The <body> tag has two attributes where you can specify backgrounds. The background can be a color or an
image.

Bgcolor

The bgcolor attribute specifies a background-color for an HTML page. The value of this attribute can be a
hexadecimal number, an RGB value, or a color name:

<body bgcolor="#000000"> <body bgcolor="rgb(0,0,0)"> <body bgcolor="black">

14
The lines above all set the background-color to black.

Background

The background attribute can also specify a background-image for an HTML page. The value of this attribute
is the URL of the image you want to use. If the image is smaller than the browser window, the image will
repeat itself until it fills the entire browser window.

<body background="clouds.gif">

<body background="http://profdevtrain.austincc.edu/html/graphics/clouds.gif">

Try It Out!

Open your text editor and type the following text:

<html>
<head> <title>My First Webpage</title> </head>
<body background="http://profdevtrain.austincc.edu/html/graphics/clouds.gif" bgcolor="#EDDD9E">
<h1 align="center">My First Webpage</h1>
<p>Welcome to my <strong>first</strong> webpage. I am writing this page using a text editor and
plain old html.</p>
<p>By learning html, I'll be able to create webpages like a <del>beginner</del> pro....<br> which I am
of course.</p>
</body>
</html>

3.13. HTML Colors

Color Values

Colors are defined using a hexadecimal notation for the combination of red, green, and blue color values
(RGB). The lowest value that can be given to one light source is 0 (hex #00). The highest value is 255 (hex
#FF). This table shows the result of combining red, green, and blue:

Color Names

A collection of color names is supported by most browsers.

web page: http://profdevtrain.austincc.edu/html/color_names.htm

15
Note: Only 16 color names are supported by the W3C HTML 4.0 standard (aqua, black, blue, fuchsia, gray,
green, lime, maroon, navy, olive, purple, red, silver, teal, white, and yellow).

3.14. HTML Lists

HTML provides a simple way to show unordered lists (bullet lists) or ordered lists (numbered lists).

Unordered Lists

An unordered list is a list of items marked with bullets (typically small black circles). An unordered list starts
with the <ul> tag. Each list item starts with the <li> tag.

Ordered Lists

An ordered list is also a list of items. The list items are marked with numbers. An ordered list starts with the
<ol> tag. Each list item starts with the <li> tag.

Inside a list item you can put paragraphs, line breaks, images, links, other lists, etc.

Definition Lists

Definition lists consist of two parts: a term and a description. To mark up a definition list, you need three
HTML elements; a container <dl>, a definition term <dt>, and a definition description <dd>.

Inside a definition-list definition (the <dd> tag) you can put paragraphs, line breaks, images, links, other lists,
etc ..

16
Try It Out

Open your text editor and type the following:

<html>
<head> <title>My First Webpage</title> </head>
<body bgcolor="#EDDD9E">
<h1 align="center">My First Webpage</h1>
<p>Welcome to my <strong>first</strong> webpage. I am writing this page using a text editor and
plain old html.</p>
<p>By learning html, I'll be able to create web pages like a pro....<br> which I am of course.</p>
Here's what I've learned:
<ul> <li>How to use HTML tags</li>
<li>How to use HTML colors</li>
<li>How to create Lists</li>
</ul>
</body>
</html>

3.15. HTML Links

HTML uses the <a> anchor tag to create a link to another document or web page.

The Anchor Tag and the Href Attribute

An anchor can point to any resource on the Web: an HTML page, an image, a sound file, a movie, etc.
syntax:

<a href="url">Text to be displayed</a>

The <a> tag is used to create an anchor to link from, the href attribute is used to tell the address of the
document or page we are linking to, and the words between the open and close of the anchor tag will be
displayed as a hyperlink.

3.16. The Target Attribute

With the target attribute, you can define where the linked document will be opened. By default, the link will
open in the current window. The code below will open the document in a new browser window:

<a href=http://www.austincc.edu/ target="_blank">Visit ACC!</a>

Email Links

To create an email link, you will use mailto: plus your email address. Here is a link to ACC's Help Desk:

<a href="mailto:[email protected]">Email Help Desk</a>

17
3.17. The Anchor Tag and the Name Attribute

The name attribute is used to create a named anchor. When using named anchors we can create links that
can jump directly to a specific section on a page, instead of letting the user scroll around to find what he/she
is looking for. Unlike an anchor that uses href, a named anchor doesn't change the appearance of the text
(unless you set styles for that anchor) or indicate in any way that there is anything special about the text.

syntax:

<a name="top">Text to be displayed</a>

To link directly to the top section, add a # sign and the name of the anchor to the end of a URL, like this:

3.18. HTML Images

The Image Tag and the Src Attribute The <img> tag is empty, which means that it contains attributes only
and it has no closing tag. To display an image on a page, you need to use the src attribute. Src stands for
"source". The value of the src attribute is the URL of the image you want to display on your page. The syntax
of defining an image:

The Alt Attribute

The alt attribute is used to define an alternate text for an image. The value of the alt attribute is author-
defined text:

<img src="graphics/chef.gif" alt="Smiling Happy Chef ">

Image Dimensions

When you have an image, the browser usually figures out how big the image is all by itself. If you put in the
image dimensions in pixels however, the browser simply reserves a space for the image, then loads the rest
of the page. Once the entire page is loads it can go back and fill in the images. Without dimensions, when it
runs into an image, the browser has to pause loading the page, load the image, then continue loading the
page. The chef image would then be:

<img src="graphics/chef.gif" width="130" height="101" alt="Smiling Happy Chef">

18
Try It Out

<html>
<head> <title>My First Webpage</title> </head>
<body>
<h1 align="center">My First Web page</h1>
<p>Welcome to my first webpage. I am writing this page using a text editor and plain old html.</p>
<p>By learning html, I'll be able to create web pages like a pro....<br> which I am of course.</p>
<!-- Who would have guessed how easy this would be :) -->
<p><img src="graphics/chef.gif" width="130" height="101" alt="Smiling Happy Chef"
align="center"></p>
<p align="center">This is my Chef</p>
</body>
</html>

3.19. Tables

Tables are defined with the <table> tag. A table is divided into rows (with the <tr> tag), and each row is
divided into data cells (with the <td> tag). The letters td stands for table data, which is the content of a data
cell. A data cell can contain text, images, lists, paragraphs, forms, horizontal rules, tables, etc.

Tables and the Border Attribute

To display a table with borders, you will use the border attribute.

Open up your text editor. Type in your <html>, <head> and <body> tags. From here on I will only be writing
what goes between the <body> tags. Type in the following:

19
<table border="1">
<tr>
<td>Tables can be used to layout information</td>
<td>&nbsp; <img src="http://profdevtrain.austincc.edu/html/graphics/chef.gif"> &nbsp; </td>
</tr>
</table>

Headings in a Table
Headings in a table are defined with the <th> tag.

Cell Padding and Spacing

The <table> tag has two attributes known as cellspacing and cellpadding. Here is a table example without
these properties. These properties may be used separately or together.

Cellspacing is the pixel width between the individual data cells in the table (The thickness of the lines making
the table grid). The default is zero. If the border is set at 0, the cellspacing lines will be invisible.

Cellpadding is the pixel space between the cell contents and the cell border. The default for this property is
also zero. This feature is not used often, but sometimes comes in handy when you have your borders turned
on and you want the contents to be away from the border a bit for easy viewing. Cellpadding is invisible,
even with the border property turned on. Cellpadding can be handled in a style sheet.

20
Table Tags

Table Size

Table Width : The width attribute can be used to define the width of your table. It can be defined as a fixed
width or a relative width. A fixed table width is one where the width of the table is specified in pixels.

For example, this code, <table width="550">, will produce a table that is 550 pixels wide. A relative table
width is specified as a percentage of the width of the visitor's viewing window. Hence this code, <table
width="80%">, will produce a table that occupies 80 percent of the screen.

HTML Layout - Using Tables

One very common practice with HTML is to use HTML tables to format the layout of an HTML page. A part of
this page is formatted with two columns. As you can see on this page, there is a left column and a right
column. This text is displayed in the left column.

An HTML <table> is used to divide a part of this Web page into two columns. The trick is to use a table
without borders, and maybe a little extra cell-padding. No matter how much text you add to this page, it will
stay inside its column borders.

21
Try It Out!

Let's put everything you've learned together to create a simple page. Open your text editor and type the
following text:

<html>
<head> <title>My First Web Page </title> </head>
<body>
<table width="90%" cellpadding="5" cellspacing="0" >
<tr bgcolor="#EDDD9E">
<td width="200" valign="top"> <img src="graphics/contact.gif" width="100"
height="100"></td>
<td valign="top">
<h1 align="right">Janet Doeson</h1>
<h3 align="right">Technical Specialist</h3></td> </tr>
<tr>
<td width="200">
<h3>Menu</h3>
<ul>
<li> <a href="home.html">Home</a></li>
<li> <a href="faq.html">FAQ</a></li>
<li> <a href="contact.html">Contact</a></li>
<li> <a href="http://www.austincc.edu">Links</a> </li>
</ul>
</td>
<td valign="top">
<h2 align="center">Welcome!</h2>
<p>Welcome to my first webpage. I created this webpage without the assistance of a webpage
editor. Just my little text editor and a keen understanding of html.</p>
<p>Look around. Notice I'm able to use paragraphs, lists and headings. You may not be able to
tell, but the layout is done with a table. I'm very clever. </p>
<blockquote>
<p>I always wanted to be somebody, but now I realize I should have been more specific.</p>
<cite>Lily Tomlin </cite>
</blockquote>
</td>
</tr>
</table>
<hr width="90%" align="left">
<address>
Janet Doeson<br>
Technical Specialist<br>
512.555.5555
</address>
<p>Contact me at <a href="mailto:[email protected]">[email protected]</a> </p>
</body>
</html>

22
3.20. Using Frames

Frames divide a browser window into two or more separate pieces or panes, with each pane containing a
separate web page. One of the key advantages that frames offer is that you can load and reload single panes
without having to reload the entire contents of the browser window. A collection of frames in the browser
window is known as a frameset.
A frameset divides the window into rows and columns (rather like a table). The simplest of framesets might
just divide the screen into three columns, whereas a complex frameset could use several rows and columns.
There is also a special kind of frame called an iframe which is a single window that can sit anywhere inside a
page.

Try It Out!

Frame1.html Frame2.html

<html> <html>
<head> <head>
<title>Untitled <title>Untitled
Document</title> Document</title>
</head> </head>
<body> <body>
This is frame 1 This is frame 2
</body> </body>
</html> </html>

Frame.html Index.html

<html> <html >


<head> <head>
<title>Untitled Document</title> <title>Untitled Document</title>
</head> </head>
<frameset cols="20%,30%,*"> <frameset cols="80,*" frameborder="no"
<frame src="frame1.html" /> border="0" framespacing="0">
<frame src="frame2.html" /> <frame src="frame1.html" name="leftFrame"
<frame src="frame1.html" /> scrolling="No" noresize="noresize" id="leftFrame"
</frameset> />
<noframes>Your Browser Don’t <frame src="frame2.html" name="mainFrame"
Support Frame</noframes> id="mainFrame" />
</html> </frameset>
<noframes>
<body>
</body>
</noframes>
</html>

23
3.21. Using HTML Form Tag

Almost every time you want to collect information from a visitor to your site, you need to use a form. Many
of the forms you will fill out online bear a strong resemblance to paper forms you have to fill out. On paper,
forms are made up of areas to enter text, boxes to check (or tick), options to choose from, and so on.
Similarly, on the Web you can create a form by combining what are known as form controls , such as
textboxes (to enter text into), checkboxes (to place a cross in), select boxes and radio buttons (to choose
from different options), and so on.

3.21.1. <FORM> Element

Every Form begins with a <FORM>tag, which can be located anywhere in the body of the HTML document.
The <FORM>tag normally has two attributes, Method and Action.
<FORM method=”Post” action=”/abc/ghf”>
Method
Post - “Post” means to send the form entry result as a document.
Get - “Get” means to submit the result as part to the URL header.
Its syntax is:
<FORM>
...
Input element
...
</FORM>

3.21.2 <INPUT> Element


3.21.2.1. Text field

Name<INPUT type=”text” name=”txt1” size=”20” maxlength=”30”>


Where size=20 mean the width of the text box characters and maxlength determines the number of
characters the user is allowed to type into the text box.

24
Try It Out!

<html>
<head>
<title>FORM Text</title>
</head>
<body>
<form>
First Name:<input type=”text” name=”txtfirst”><br><br>
Last Name:<input type=”text” name=”txtlast”><br><br>
</form >
</body></html>
3.21.2.2. Password field

If you want the user to enter text without it being display on the screen, you can use <INPUT
TYPE=”password”>.

Asterisks(***) are displayed in place of the text the user types.

Try It Out!

<html>
<head>
<title>FORM Text</title>
</head>
<body>
<form>
Username:<input type=”text” name=”txtUsername”><br><br>
Password:<input type=”password” name=”pwdPassword”><br><br>
Confirm:<input type="password">
</form >
</body>
</html>

3.21.2.3. Radio Buttons


Radio buttons are used for only one choice. Including checked attribute makes the option selected by
default.

3.21.2.4. Check box


Checkboxs let a user ONE or MORE options of a limited number of choices.

3.21.2.5. Submit Button


Every set of Form tags requires a Submit button. This is a element that causes the browser to send
the names and values of the other elements to the CGI application specified by the ACTION
attributes of the FORM element.

3.21.3. <TEXTAREA>Element
In a text area the user can write an unlimited number of characters. The size of a textarea can be
specified by the cols and rows attributes.

25
3.21.4. <LABEL>Element
The <label> tag defines a label for an input element. You should use the < label > element. This
element does not affect the form in any way other than telling users what information they should be
entering.

3.21.5. <FIELDSET> and <LEGENT> Element

The < fieldset > element creates a border around the group of form controls to show that they are
related.
The < legend > element allows you to specify a caption for the < fieldset > element, which acts as a
title for the group of form controls. When used, the < legend > element should always be the first
child of the < fieldset > element.

3.21.6. <SELECT> Element


The <select> tag is used to create a select list.(drop-down list) The <option> tags inside the
select element define the available options in the list.
Its syntax is:
<SELECT>
<OPTION>pencil</OPTION>
<OPTION>pen</OPTION>
<OPTION>book</OPTION>
</SELECT>

3.21.7. <OPTIONGROUP> Element

If you have a very long list of items in a select box, you can group them together using the
<optgroup> element, which acts just like a container element for all the elements you want within a
group.
The <optgroup>element can carry a label attribute whose value is a label for that group of options.

3.21.8. <OPTION> Element

Inside any <select> element, you will find at least one <option> element. The text between
the opening <option> and closing </option> tags is displayed to the user as the label for that option.

Try It Out!

26
Answer:
<?xml version=”1.0” ?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” lang=”en” xml:lang=”en” >
<head>
<title> Contact Us </title>
</head>
<body>
<h1> Contact Us </h1>
<p> Use the following form to send a message to Example Cafe </p>
<table>
<tr>
<td> Your email </td>
<td> <input type=”text” name=”txtFrom” id=”emailFrom” size=”20” maxlength=”250” /> </td>
</tr>
<tr>
<td> Message </td>
<td> <textarea name=”txtBody” id=”emailBody” cols=”50” rows=”10”> </textarea> </td>
</tr>
<tr>
<td> How did you hear of us? </td>
<td>
<select name=”selReferrer”>
<option value=”google”> Google </option>
<option value=”ad” > Local newspaper ad </option>
<option value=”friend”> Friend </option>
<option value=”other”> Other </option>
</select>
</td>
</tr>
<tr>
<td> Newsletter </td>

<td> <input type="checkbox" name="chkBody" id="newsletterSignup" checked="checked" />


Ensure this box is checked if you would like to receive email updates </td>
</tr>
</table>
<input type="submit" value="Send message" />
</body>
</html>

27
Exercises

1- Create Your Own Page

It’s time to create your own page. Use your text editor to create a page which contains the following:

 the required HTML page codes


 link to another web page
 an email link
 a picture/graphic
 a list of information

2-

1. Look back at the Try It Out example where you created a menu, and create a new page that links directly
to each course on the menu. Then add a link to the main Wrox web site ( www.wrox.com) . The page should
look something like Figure.

2. Go back to the pages in the sample application and make sure that you have updated the navigation for
each page.

Answer

Navigation for the homepage:

< div > HOME < a href=”menu.html” > MENU < /a > < a href=”recipes.html” > RECIPES < /a >
< a href=”contact.html” > CONTACT < /a > < /div >

Navigation for the menu page:

< div > < a href=”index.html” > HOME < /a > MENU < a href=”recipes.html” > RECIPES < /a >
< a href=”contact.html” > CONTACT < /a > < /div >

Navigation for the recipes page:

< div > < a href=”index.html” > HOME < /a > < a href=”menu.html” > MENU < /a > RECIPES
< a href=”contact.html” > CONTACT < /a > < /div >

Navigation for the contact page:

< div > < a href=”index.html” > HOME < /a > < a href=”menu.html” > MENU < /a > <a
href=”recipes.html” > RECIPES < /a > CONTACT < /div >

28
3–

Where should the < caption > element for a table be placed in the document and, by default, where is it
displayed?

Answer

<HTML>
<HEAD>
<TITLE>Example Paragraph</TITLE>
</HEAD>
<BODY>
<TABLE border="1">
<CAPTION>YEAR, MONTH, DAY</CAPTION>
<TR>
<TH>YEAR</TH>
<TH>MONTH</TH>
<TH>DAY</TH>
</TR>
<TR>
<TH>2016</TH>
<TH>march</TH>
<TH>10</TH>
</TR>
<TR>
<TH>2018</TH>
<TH>january</TH>
<TH>25</TH>
</TR>
</TABLE>
</BODY>
</HTML>

4-

29
Answer

<HTML>
<HEAD>
<TITLE>label</TITLE>
</HEAD>
<BODY>
<form>
<fieldset>
<legend> <em> Contact Information </em> </legend>
<label> First name: <input type=”text” name=”txtFName” size=”20” />
</label> <br/><br/>
<label> Last name: <input type=”text” name=”txtLName” size=”20” /> </label>
<br/><br/>
<label> E-mail: <input type=”text” name=”txtEmail” size=”20” /> </label>
<br/><br/>
<fieldset>
<fieldset>
<legend> <em> Competition Question </em> </legend>
How tall is the Eiffel Tower in Paris, France? <br/>
<label> <input type="radio" name=”radAnswer” value="584"/>
584ft </label> <br/>
<label> <input type="radio" name=”radAnswer” value="784"/>
784ft </label> <br/>
<label> <input type="radio" name=”radAnswer” value="984"/>
984ft </label> <br/>
<label> <input type="radio" name=”radAnswer” value="1184"/>
1184ft </label> <br />

</fieldset>
<fieldset>
<legend> <em> Tiebreaker Question </em> </legend>

30
<label> In 25 words or less, say why you would like to win $10,000:
<textarea name=”txtTiebreaker” rows=”10” cols=”40” > </textarea>
</label>
</fieldset>
<fieldset>
<legend> <em> Enter competition </em> </legend>
<input type="submit" value="Enter Competition"/>
</fieldset>
</form>
</BODY>
</HTML>

5 - Create an e - mail feedback form that looks like the one shown in Figure

< ?xml version=”1.0” encoding=”UTF-8”? >

< !DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”


“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

< html xmlns=”http://www.w3.org/1999/xhtml” lang=”en”>

< head > < title > Reply to ad < /title > < /head >

< body >

< h2 > Reply to ad < /h2 >

< p > Use the following form to respond to the ad:< /p >

< form action=”http://www.example.com/ads/respond.aspx” method=”post” name=”frmRespondToAd”>

< table >

< tr >

< td > < label for=”emailTo” > To < /label > < /td >

31
< td > < input type=”text” name=”txtTo” readonly=”readonly” id=”emailTo” size=”20”
value=”Star Seller” / > < /td >

< /tr >

< tr >

< td > < label for=”emailFrom” > To < /label > < /td >

< td > < input type=”text” name=”txtFrom” id=”emailFrom” size=”20” /> < /td >

< /tr >

< tr >

< td > < label for=”emailSubject” > Subject < /label > < /td >

< td > < input type=”text” name=”txtSubject” id=”emailSubject” size=”50” / > < /td >

< /tr >

< tr >

< td > < label for=”emailBody” > Body < /label > < /td >

< td > < textarea name=”txtBody” id=”emailBody” cols=”50” rows=”10”>< /textarea > </td >

< /tr >

< /table >

< input type=”submit” value=”Send email” />

< /form >

< /body >

< /html >

32
Chapter (4)

Cascading Style Sheets

1. Before you continue you should have a basic understanding of the following: HTML / XHTML
2. To learn how to use cascading style sheets (or CSS for short) to take control of the style of your pages,
including the colors and size of fonts, the width and colors of lines, and the amount of space between
items on the page.
3. The cascading style sheets specification works by allowing you to specify rules that say how the
content of elements within your document should appear.

4.1. Introduction to CSS

What is CSS?
 CSS stands for Cascading Style Sheets
 Styles define how to display HTML elements
 Styles were added to HTML 4.0 to solve a problem
 External Style Sheets can save a lot of work
 External Style Sheets are stored in CSS files

Styles Solved a Big Problem

 HTML was never intended to contain tags for formatting a document.


 HTML was intended to define the content of a document, like:
 <h1>This is a heading</h1>
 <p>This is a paragraph.</p>
 When tags like <font>, and color attributes were added to the HTML 3.2 specification, it started a
nightmare for web developers. Development of large web sites, where fonts and color information
were added to every single page, became a long and expensive process.
 To solve this problem, the World Wide Web Consortium (W3C) created CSS. In HTML 4.0, all
formatting could be removed from the HTML document, and stored in a separate CSS file.
 All browsers support CSS today.

CSS Saves a Lot of Work!

 CSS defines HOW HTML elements are to be displayed.


 Styles are normally saved in external .css files. External style sheets enable you to change the
appearance and layout of all the pages in a Web site, just by editing one single file!

4.1.1 Basic syntax and structure

CSS Syntax

A CSS rule has two main parts: a selector, and one or more declarations:

33
 The selector is normally the HTML element you want to style.
 Each declaration consists of a property and a value.
 The property is the style attribute you want to change.
 Each property has a value.

CSS Example:

CSS declarations always end with a semicolon, and declaration groups are surrounded by curly brackets:

p {color:red;text-align:center;}

To make the CSS more readable, you can put one declaration on each line, like this:

Example:
P
{
color:red;
text-align:center;
}

CSS Comments

Comments are used to explain your code, and may help you when you edit the source code at a later date.
Comments are ignored by browsers.

A CSS comment begins with "/*", and ends with "*/", like this:
/*This is a comment*/
P
{
text-align:center; /*This is another comment*/
color:black; font-family:arial;
}

4.1.2 Basic CSS Selectors


There are three types of selectors in CSS
• Element: can be selected using it’s name e.g. ‘p’, ‘div’ and ‘h1’ etc.
• Class: can be selected using ‘.className’ operator e.g. ‘.h3_blue’.
• ID: can be selected using ‘#idName’ e.g. ‘#my_para’.
We will use following HTML for understanding the selectors

<!- - css.html - ->


<!DOCTYPE html>
<html>
<head><title>CSS Selector</title>
<link rel=”stylesheet” type=”text/css” href=”asset/css/my_css.css>
</head>
<body>
<h3>CSS Selector</h3>
<p class=’c_head’> Paragraph with class ‘c_head’ </p>
<p class=’i_head’> Paragraph with id ‘i_head’ </p>
</body></html>
34
/* asset/css/my_css.css */

/*element selection*/
h3{color: blue;
}

/*class selection*/

.c_head{
font-family: cursive;
color: orange;
}

/*id selection*/

#i_head{
font-variant: small-caps;
Color: red;
}

4.1.3 Inline Styles , Internal Style Linking External Style

4.1.3.1. Inline CSS

 Below code is an example of ‘inline CSS’, where the styles are defined inside the individual tags.

!--css.html-->
<!DOCTYPE html>
<html>
<head>
<title>CSS Tutorial</title>
</head>
<body>
<h3 style ="color:blue"> Heading 1 </h3>
<h3 style ="color:blue"> Heading 3 </h3>
<h3 style = "color:blue"> Heading 3 </h3>
</body>
</html>
4.1.3.2. Internal Style CSS
CSS enclosed in <style></style> tags within an HTML document functions like an external stylesheet, except
that it lives in the HTML document it styles instead of in a separate file, and therefore can only be applied to
the document in which it lives.
In the below code, the style is embedded inside the ‘style’ tag. Here, we have defined two classes i.e.
‘h3_blue (Lines 21-23)’ and ‘h3_red (Lines 26-28)’.

Note:
 In CSS, the comments are written between /* and */
 CSS has three parts,
– Selectors e.g. p, h3.h3_blue
– Properties e.g. color
– Values of properties e.g. red

35
<!- - css.html - ->
<!DOCTYPE html>
<html>
<head>
<title> CSS Tutorial </title>
<style type=”text/css”>
H3.h3_blue { /*change color to blue*/
Color: blue;
}
H3.h3_red{ /*/*change color to blue*/
Color: red;
}
</style>
<head>
<body>
<h3 class=’h3_blue’> Heading 1 </h3>
<h3 class=’h3_blue’> Heading 3 </h3>
<h3 class=’h3_blue’> Heading 3 </h3>
<h3 class=’h3_red’> Heading 1 </h3>
<h3 class=’h3_red’> Heading 3 </h3>
<h3 class=’h3_red’> Heading 3 </h3>
</body>
</html>

4.1.3.3. External CSS


We can write the ‘CSS’ code in different file and then import the file into ‘html’ document as shown in this
section. In this way, we can manage the files easily.
•The ‘CSS’ code is saved in the file ‘my_css.css’ which is saved inside the folder asset/css’

/* asset/css/my_css.css */ <!DOCTYPE html>


<html>
h3.h3_blue
{ <head>
color:blue; <title>CSS Tutorial</title>
}
<link rel="stylesheet" type="text/css"
h3.h3_red
href="asset/css/my_css.css">
{
color:red; </head>
} <body>
<h3 class='h3_blue'> Heading 1 </h3>
<h3 class='h3_blue'> Heading 3 </h3>
<h3 class='h3_blue'> Heading 3 </h3>
<h3 class='h3_red'> Heading 1 </h3>
<h3 class='h3_red'> Heading 3 </h3>
<h3 class='h3_red'> Heading 3 </h3>
</body>
</html>

36
4.2. CSS Styling

4.2.1. CSS Backgrounds

CSS background properties are used to define the background effects of an element.

CSS properties used for background effects:

• background-color
• background-image
• background-repeat
• background-attachment
• background-position

Background Color

The background-color property specifies the background color of an element.

The background color of a page is defined in the body selector:

Example:
body {background-color:#b0c4de;}
The background color can be specified by:

• name - a color name, like "red"


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

In the example below, the h1, p, and div elements have different background colors:

Example:
h1 {background-color:#6495ed;}
p {background-color:#e0ffff;}

div {background-color:#b0c4de;}

Background Image

The background-image property specifies an image to use as the background of an element.

By default, the image is repeated so it covers the entire element.

Example:
body {background-image:url('paper.gif');}

Background Image - Repeat Horizontally or Vertically


By default, the background-image property repeats an image both horizontally and vertically. Some images
should be repeated only horizontally or vertically, or they will look strange, like this:

If the image is repeated only horizontally (repeat-x), the background will look better:

37
Example:

body { background-image:url('gradient2.png');

background-repeat:repeat-x; }

Background Image - Set position and no-repeat

When using a background image, use an image that does not disturb the text.

Showing the image only once is specified by the background-repeat property:

Example:

body { background-image:url('img_tree.png');

background-repeat:no-repeat; }

In the example above, the background image is shown in the same place as the text. We want to change the
position of the image, so that it does not disturb the text too much.

The position of the image is specified by the background-position property:

Example:

body { background-image:url('img_tree.png');

background-repeat:no-repeat;

background-position:top right; }

Background-attachment

The background-attachment property sets whether a background image is fixed or scrolls with the rest of the
page.

body { background-image: url('img.jpg'); background-attachment: fixed; }

Value Description
scroll The background scrolls along with the element. This is default.
fixed The background is fixed with regard to the viewport.
local The background scrolls along with the element's contents.
initial Sets this property to its default value.
inherit Inherits this property from its parent element.

Examples

background-attachment: scroll

The default behaviour, when the body is scrolled the background scrolls with it:

body { background-image: url('image.jpg'); background-attachment: scroll; }

38
background-attachment: fixed

The background image will be fixed and will not move when the body is scrolled:

body { background-image: url('image.jpg'); background-attachment: fixed; }

background-attachment: local

The background image of the div will scroll when the contents of the div is scrolled.

div { background-image: url('image.jpg'); background-attachment: local; }

Background-position

The background-position property is used to specify the starting position for a background image or gradient

.myClass { background-image: url('path/to/image.jpg'); background-position: 50% 50%; }

The position is set using an X and Y co-ordinate and be set using any of the units used within CSS.

Unit Description
value% value% A percentage for the horizontal offset is relative to (width of background positioning
area - width of background image). A percentage for the vertical offset is relative to
(height of background positioning area - height of background image) The size of the
image is the size given by background-size.
valuepx valuepx Offsets background image by a length given in pixels relative to the top left of the
background positioning area

Background - Shorthand property

There are many properties to consider when dealing with backgrounds.

Example:
body {background:#ffffff url('img_tree.png') no-repeat top right;}
When using the shorthand property the order of the property values are:

• background-color
• background-image
• background-repeat
• background-attachment
• background-position

39
All CSS Background Properties

The number in the "CSS" column indicates in which CSS version the property is defined (CSS1 or CSS2).

4.2.1. CSS Text

TEXT FORMATTING

This text is style with some of the text formatting properties. The heading uses the text-align, text-transform,
and color properties. The paragraph is indented, aligned, and the space between characters is species.

Text Color

The color property is used to set the color of the text. The color can be specified by:

 name - a color name, like "red"


 RGB - an RGB value, like "rgb(255,0,0)"
 Hex - a hex value, like "#ff0000"

The default color for a page is defined in the body selector.


Example:
body {color:blue;}
h1 {color:#00ff00;}
h2 {color:rgb(255,0,0);}

40
Text Alignment

The text-align property is used to set the horizontal alignment of a text. Text can be centered, or aligned to
the left or right, or justified. When text-align is set to "justify", each line is stretched so that every line has
equal width, and the left and right margins are straight (like in magazines and newspapers).

Example:

h1 {text-align:center;}

p.date {text-align:right;}

p.main {text-align:justify;}

Text Decoration

The text-decoration property is used to set or remove decorations from text.

The text-decoration property is mostly used to remove underlines from links for design purposes:

Example:

a {text-decoration:none;}

It can also be used to decorate text:

Example:

h1 {text-decoration:overline;}

h2 {text-decoration:line-through;}

h3 {text-decoration:underline;}

h4 {text-decoration:blink;}

Text Transformation

The text-transform property is used to specify uppercase and lowercase letters in a text. It can be used to
turn everything into uppercase or lowercase letters, or capitalize the first letter of each word.

Example :

p.uppercase {text-transform:uppercase;}

p.lowercase {text-transform:lowercase;}

p.capitalize {text-transform:capitalize;}

Text Indentation

The text-indentation property is used to specify the indentation of the first line of a text.

Example:

p {text-indent:50px;}

41
Quiz:

Specify the space between characters


This example demonstrates how to increase or decrease the space between characters.
Specify the space between lines
This example demonstrates how to specify the space between the lines in a paragraph.
Set the text direction of an element
This example demonstrates how to change the text direction of an element.
Increase the white space between words
This example demonstrates how to increase the white space between words in a paragraph.
Disable text wrapping inside an element
This example demonstrates how to disable text wrapping inside an element.
Vertical alignment of an image
This example demonstrates how to set the vertical align of an image in a text.

All CSS Text Properties

42
4.2.2. CSS Font
CSS font properties define the font family, boldness, size, and the style of a text.

Difference Between Serif and Sans-serif Fonts

CSS Font Families

In CSS, there are two types of font family names:

 generic family - a group of font families with a similar look (like "Serif" or "Monospace")

43
 font family - a specific font family (like "Times New Roman" or "Arial")

Font Family

The font family of a text is set with the font-family property.

The font-family property should hold several font names as a "fallback" system. If the browser does not
support the first font, it tries the next font.

Start with the font you want, and end with a generic family, to let the browser pick a similar font in the
generic family, if no other fonts are available.

Example:

p { font-family: "Times New Roman" , Times , serif ; }

Font Style

The font-style property is mostly used to specify italic text.

This property has three values: normal - The text is shown

 normally
 italic - The text is shown in italics
 oblique - The text is "leaning" (oblique is very similar to italic, but less supported)

Example:

p.normal {font-style:normal;}

p.italic {font-style:italic;}

p.oblique {font-style:oblique;}

Font Size

The font-size property sets the size of the text. Being able to manage the text size is important in web
design. However, you should not use font size adjustments to make paragraphs look like headings, or
headings look like paragraphs. Always use the proper HTML tags, like <h1> - <h6> for headings and <p> for
paragraphs. The font-size value can be an absolute or relative size.

Absolute size:

 Sets the text to a specified size


 Does not allow a user to change the text size in all browsers (bad for accessibility reasons)

44
 Absolute size is useful when the physical size of the output is known

Relative size:

 Sets the size relative to surrounding elements


 Allows a user to change the text size in browsers

If you do not specify a font size, the default size for normal text, like paragraphs, is 16px (16px=1em).

Set Font Size With Pixels

Setting the text size with pixels, gives you full control over the text size:

Example:

h1 {font-size:40px;}

h2 {font-size:30px;}

p {font-size:14px;}

The example above allows Firefox, Chrome, and Safari to resize the text, but not Internet Explorer.

Set Font Size With Em

To avoid the resizing problem with Internet Explorer, many developers use em instead of pixels.
The em size unit is recommended by the W3C. 1em is equal to the current font size.
The default text size in browsers is 16px. So, the default size of 1em is 16px.
The size can be calculated from pixels to em using this formula: pixels/16=em
Example:

h1 {font-size:2.5em;} /* 40px/16=2.5em */
h2 {font-size:1.875em;} /* 30px/16=1.875em */
p {font-size:0.875em;} /* 14px/16=0.875em */
Quiz:

Set the boldness of the font


This example demonstrates how to set the boldness of a font.
Set the variant of the font
This example demonstrates how to set the variant of a font.
All the font properties in one declaration
This example demonstrates how to use the shorthand property for setting all of the font properties in one
declaration.

All CSS Font Properties

45
4.2.4. CSS Links

Styling Links

Links can be style with any CSS property (e.g. color, font-family, background-color).
Special for links are that they can be styled differently depending on what state they are in.
The four links states are:
 a:link - a normal, unvisited link
 a:visited - a link the user has visited
 a:hover - a link when the user mouse over it
 a:active - a link the moment it is clicked

46
Example:

a:link {color:#FF0000;} /* unvisited link */

a:visited {color:#00FF00;} /* visited link */

a:hover {color:#FF00FF;} /* mouse over link */

a:active {color:#0000FF;} /* selected link */

When setting the style for several link states, there are some order rules:

 a:hover MUST come after a:link and a:visited


 a:active MUST come after a:hover

Text Decoration

The text-decoration property is mostly used to remove underlines from links:

Example:

a:link {text-decoration:none;}

a:visited {text-decoration:none;}

a:hover {text-decoration:underline;}

a:active {text-decoration:underline;}

Background Color

The background-color property specifies the background color for links:

Example:

a:link {background-color:#B2FF99;}

a:visited {background-color:#FFFF85;}

a:hover {background-color:#FF704D;}

a:active {background-color:#FF704D;}

4.2.5. CSS List

In HTML, there are two types of lists:

 unordered lists - the list items are marked with bullets


 ordered lists - the list items are marked with numbers or letters

With CSS, lists can be styled further, and images can be used as the list item marker.

Different List Item Markers

The type of list item marker is specified with the list-style-type property:

47
Example:
ul.a {list-style-type: circle;}

ul.b {list-style-type: square;}

ol.c {list-style-type: upper-roman;}

ol.d {list-style-type: lower-alpha;}

Some of the property values are for unordered lists, and some for ordered lists.

Values for Unordered Lists

Values for Ordered Lists

An Image as The List Item Marker

To specify an image as the list item marker, use the list-style-image property:
Example:
ul
{
list-style-image: url('sqpurple.gif'); }
The example above does not display equally in all browsers. IE and Opera will display the imagemarker a
little bit higher than Firefox, Chrome, and Safari.

If you want the image-marker to be placed equally in all browsers, a crossbrowser solution is explained
below.

Crossbrowser Solution

The following example displays the image-marker equally in all browsers:

Example:

Ul
{

48
list-style-type: none; padding: 0px; margin: 0px;
}
li
{
background-image: url(sqpurple.gif);
background-repeat: no-repeat;
background-position: 0px 5px;
padding-left: 14px;
}

List - Shorthand property

It is also possible to specify all the list properties in one, single property. This is called a shorthand property.
The shorthand property used for lists is the list-style property:
Example:
ul { list-style: square url("sqpurple.gif"); }

When using the shorthand property, the orders of the values are:

 list-style-type
 list-style-position (for a description, see the CSS properties table below)
 list-style-image

All CSS List Properties

4.2.6. CSS Tables


The look of an HTML table can be greatly improved with CSS:

Table Borders

To specify table borders in CSS, use the border property.

The example below specifies a black border for table, th, and td elements:

Example:

table, th, td
{

49
border: 1px solid black;
}

To display a single border for the table, use the border-collapse property.

Collapse Borders

The border-collapse property sets whether the table borders are collapsed into a single border or separated:

Example:
table
{
border-collapse:collapse; }
table,th, td
{
border: 1px solid black; }

Table Width and Height

Width and height of a table is defined by the width and height properties.
The example below sets the width of the table to 100%, and the height of the th elements to 50px:
Example:
table
{
width:100%; }
th
{
height:50px; }

Table Text Alignment


The text in a table is aligned with the text-align and vertical-align properties.
The text-align property sets the horizontal alignment, like left, right, or center:
Example:
td { text-align:right; }
The vertical-align property sets the vertical alignment, like top, bottom, or middle:
Example:
td { height:50px; vertical-align:bottom; }
Table Padding
To control the space between the border and content in a table, use the padding property on td and th
elements:
Example: td { padding:15px; }

Table Color
The below specifies the color of the borders, and the text and background color of th elements:
Example:
table, td, th { border:1px solid green;}

50
th { background-color:green; color:white; }

4.3. CSS Box Model


4.3.1 Box model
All HTML elements can be considered as boxes. In CSS, the term "box model" is used when talking about
design and layout. The CSS box model is essentially a box that wraps around HTML elements, and it consists
of: margins, borders, padding, and the actual content.
The box model allows us to place a border around elements and space elements in relation to other
elements. The image below illustrates the box model:

 Margin - Clears an area around the border. The margin does not have a background color, and it is
completely transparent
 Border - A border that lies around the padding and content. The border is affected by the background
color of the box
 Padding - Clears an area around the content. The padding is affected by the background color of the box
 Content - The content of the box, where text and images appear
Width and Height of an Element
Important: When you specify the width and height properties of an element with CSS, you are just setting
the width and height of the content area. To know the full size of the element, you must also add the
padding, border and margin.
The total width of the element in the example below is 300px:
width:250px; border:5px solid gray;
padding:10px; margin:10px;

Let's do the math:


250px (width)
+ 20px (left and right padding)
+ 10px (left and right border)
+ 20px (left and right margin)
= 300px

Imagine that you only had 250px of space. Let's make an element with a total width of 250px:
Example:

51
width:220px;
padding:10px;
border:5px solid gray;
margin:0px;
The total width of an element should always be calculated like this:
Total element width = width + left padding + right padding + left border + right border + left margin + right
margin
The total height of an element should always be calculated like this:
Total element height = height + top padding + bottom padding + top border + bottom border + top margin +
bottom margin

4.3.2. CSS Border


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

Border Width
The border-width property is used to set the width of the border.
The width is set in pixels, or by using one of the three pre-defined values: thin, medium, or thick.
Note: The "border-width" property does not work if it is used alone. Use the "border-style" property to set
the borders first.
Example:
p.one { border-style:solid; border-width:5px; }
p.two { border-style:solid; border-width:medium; }

Border Color
The border-color property is used to set the color of the border.
The color can be set by: name - specify a color name, like "red"
• RGB - specify a RGB value, like "rgb(255,0,0)"
• Hex - specify a hex value, like "#ff0000"

52
You can also set the border color to "transparent".
Example:
p.one { border-style:solid; border-color:red; }
p.two { border-style:solid; border-color:#98bf21; }

Border - Individual sides


In CSS it is possible to specify different borders for different sides:
Example:
p
{
border-top-style:dotted;
border-right-style:solid;
border-bottom-style:dotted;
border-left-style:solid;
}
The example above can also be set with a single property:
Example:
border-style:dotted solid;

The border-style property can have from one to four values.


border-style:dotted solid double dashed;
 top border is dotted
 right border is solid
 bottom border is double
 left border is dashed
border-style:dotted solid double;
 top border is dotted
 right and left borders are solid
 bottom border is double
border-style:dotted solid;
 top and bottom borders are dotted
 right and left borders are solid
border-style:dotted;
 all four borders are dotted

Border - Shorthand property


As you can see from the examples above, there are many properties to consider when dealing with borders.
To shorten the code, it is also possible to specify all the border properties in one property. This is called a
shorthand property.
The shorthand property for the border properties is "border":
Example border:
5px solid red;
When using the border property, the orders of the values are:
 border-width

53
 border-style
 border-color
It does not matter if one of the values above are missing (although, border-style is required), as long as the
rest are in the specified order.

Quiz:
All the top border properties in one declaration
This example demonstrates a shorthand property for setting all of the properties for the top border in one
declaration.
Set the style of the bottom border
This example demonstrates how to set the style of the bottom border.
Set the width of the left border
This example demonstrates how to set the width of the left border.
Set the color of the four borders
This example demonstrates how to set the color of the four borders. It can have from one to four colors.
Set the color of the right border
This example demonstrates how to set the color of the right border.

All CSS Border Properties

54
4.3.3. CSS Outline
An outline is a line that is drawn around elements, outside the border edge, to make the element "stand
out".
The outline property specifies the style, color, and width of an outline.

Quiz:
Draw a line around an element (outline)
This example demonstrates how to draw a line around an element, outside the border edge.
Set the style of an outline
This example demonstrates how to set the style of an outline.
Set the color of an outline
This example demonstrates how to set the color of an outline.

All CSS Outline Properties

55
4.3.4. CSS Margin
The CSS margin properties define the space around elements.
Margin The margin clears an area around an element (outside the border). The margin does not have a
background color, and is completely transparent.
The top, right, bottom, and left margin can be changed independently using separate properties. A
shorthand margin property can also be used, to change all margins at once.
Possible Values

Margin - Individual sides In CSS, it is possible to specify different margins for different sides:
Example:
margin-top:100px;
margin-bottom:100px;
margin-right:50px;
margin-left:50px;

Margin - Shorthand property


To shorten the code, it is possible to specify all the margin properties in one property.
This is called a shorthand property. The shorthand property for all the margin properties is "margin":
Example:
margin:100px 50px;
The margin property can have from one to four values.
margin: 25px 50px 75px 100px;
 top margin is 25px
 right margin is 50px
 bottom margin is 75px
 left margin is 100px
margin: 25px 50px 75px;
 top margin is 25px
 right and left margins are 50px
 bottom margin is 75px
margin: 25px 50px;
 top and bottom margins are 25px
 right and left margins are 50px
margin: 25px;
 all four margins are 25px
Quiz:
Set the top margin of a text using a cm value
This example demonstrates how to set the top margin of a text using a cm value.
Set the bottom margin of a text using a percent value

56
This example demonstrates how to set the bottom margin of a text using a percent value.

All CSS Margin Properties

4.3.5. CSS Padding


The CSS padding properties define the space between the element border and the element content.
Padding
The padding clears an area around the content (inside the border) of an element. The padding is affected by
the background color of the element.
The top, right, bottom, and left padding can be changed independently using separate properties. A
shorthand padding property can also be used, to change all paddings at once.
Possible Values

Padding - Individual sides


In CSS, it is possible to specify different padding for different sides:
Example:
padding-top:25px;
padding-bottom:25px;
padding-right:50px;
padding-left:50px;

Padding - Shorthand property


To shorten the code, it is possible to specify all the padding properties in one property. This is called a
shorthand property.
The shorthand property for all the padding properties is "padding":

57
Example:
padding:25px 50px;
The padding property can have from one to four values.
padding: 25px 50px 75px 100px;
 top padding is 25px
 right padding is 50px
 bottom padding is 75px
 left padding is 100pxŃ
padding: 25px 50px 75px;
 top padding is 25px
 right and left paddings are 50px
 bottom padding is 75px
padding: 25px 50px;
 top and bottom paddings are 25px
 right and left paddings are 50px
padding: 25px;
 all four paddings are 25px

4.4. CSS Advanced


4.4.1. CSS Positioning
The CSS positioning properties allow you to position an element. It can also place an element behind
another, and specify what should happen when an element's content is too big. Elements can be positioned
using the top, bottom, left, and right properties.
There are four different positioning methods.
Static Positioning
HTML elements are positioned static by default. A static positioned element is always positioned according
to the normal flow of the page.
Static positioned elements are not affected by the top, bottom, left, and right properties.
Fixed Positioning
An element with fixed position is positioned relative to the browser window. It will not move even if the
window is scrolled:
Example:
p.pos_fixed { position:fixed; top:30px; right:5px; }
Fixed positioned elements are removed from the normal flow. The document and other elements behave
like the fixed positioned element does not exist. Fixed positioned elements can overlap other elements.
Relative Positioning
A relative positioned element is positioned relative to its normal position.
Example:
h2.pos_left { position:relative; left:-20px; }
h2.pos_right {position:relative; left:20px; }

58
The content of a relatively positioned elements can be moved and overlap other elements, but the reserved
space for the element is still preserved in the normal flow.
Example:
h2.pos_top { position:relative; top:-50px; }
Relatively positioned element are often used as container blocks for absolutely positioned elements.
Absolute Positioning
An absolute position element is positioned relative to the first parent element that has a position other than
static. If no such element is found, the containing block is <html>:
Example:
h2 { position:absolute; left:100px; top:150px; }
Absolutely positioned elements are removed from the normal flow. The document and other elements
behave like the absolutely positioned element does not exist.
Absolutely positioned elements can overlap other elements.

Overlapping Elements
When elements are positioned outside the normal flow, they can overlap other elements.
The z-index property specifies the stack order of an element (which element should be placed in front of, or
behind, the others).
An element can have a positive or negative stack order:
Example:
img { position:absolute; left:0px; top:0px; z-index:-1 }

An element with greater stack order is always in front of an element with a lower stack order.

Quiz:
Set the shape of an element
This example demonstrates how to set the shape of an element.
The element is clipped into this shape, and displayed.
How to show overflow in an element using scroll
This example demonstrates how to set the overflow property to create a scroll bar when an element's
content is too big to fit in a specified area.
How to set the browser to automatically handle overflow
This example demonstrates how to set the browser to automatically handle overflow.
Change the cursor
This example demonstrates how to change the cursor.

All CSS Positioning Properties

59
4.4.2. CSS Navigation Bar
Demo: Navigation Bar

Navigation Bars
Having easy-to-use navigation is important for any web site. With CSS you can transform boring HTML
menus into good-looking navigation bars.
Navigation Bar = List of Links
A navigation bar needs standard HTML as a base.
In our examples we will build the navigation bar from a standard HTML list.
A navigation bar is basically a list of links, so using the <ul> and <li> elements makes perfect sense:
Example:
<ul>

60
<li><a href="default.asp">Home</a></li>
<li><a href="news.asp">News</a></li>
<li><a href="contact.asp">Contact</a></li>
<li><a href="about.asp">About</a></li>
</ul>
Now let’s remove the bullets and the margins and padding from the list:
Example:
ul { list-style-type:none; margin:0; padding:0; }
Example explained:
 list-style-type:none - Removes the bullets. A navigation bar does not need list markers
 Setting margins and padding to 0 to remove browser default settings
The code in the example above is the standard code used in both vertical and horizontal navigation bars.
Vertical Navigation Bar
To build a vertical navigation bar we only need to style the <a> elements, in addition to the code above:
Example:
a { display:block; width:60px; }
Example explained:
 display:block - Displaying the links as block elements makes the whole link area clickable (not just
the text), and it allows us to specify the width
 width:60px - Block elements take up the full width available by default. We want to specify a 60 px
width
Horizontal Navigation Bar
There are two ways to create a horizontal navigation bar. Using inline or floating list items. Both methods
work fine, but if you want the links to be the same size, you have to use the floating method.
Inline List Items
One way to build a horizontal navigation bar is to specify the <li> elements as inline, in addition to the
"standard" code above:
Example:
li { display:inline; }
Example explained:
 display:inline; - By default, <li> elements are block elements. Here, we remove the line breaks before
and after each list item, to display them on one line
Floating List Items
In the example above the links have different widths. For all the links to have an equal width, float the <li>
elements and specify a width for the <a> elements:
Example:
li { float:left; } a { display:block; width:60px; }
Example explained:
 float:left - use float to get block elements to slide next to each other
 display:block - Displaying the links as block elements makes the whole link area clickable (not just
the text), and it allows us to specify the width

61
 width:60px - Since block elements take up the full width available, they cannot float next to each
other. We specify the width of the links to 60px

4.4.3. CSS Rounded Corners


CSS border-radius Property

The CSS border-radius property defines the radius of an element's corners.


Here are three examples:
1. Rounded corners for an element with a specified background color:

2. Rounded corners for an element with a border:

3. Rounded corners for an element with a background image:

CSS Rounded Corners Properties

4.4.4. CSS Shadow Effects

With CSS you can add shadow to text and to elements.


In this chapter you will learn about the following properties:
 text-shadow

62
 box-shadow

CSS Text Shadow


The CSS text-shadow property applies shadow to text.
In its simplest use, you only specify the horizontal shadow (2px) and the vertical shadow (2px):

Example:
h1 {
   color: white;
  text-shadow: 2px 2px 4px #000000;
}

Multiple Shadows
To add more than one shadow to the text, you can add a comma-separated list of shadows.
The following example shows a red and blue neon glow shadow:

Example:
h1 {
color: white;
   text-shadow: 1px 1px 2px black, 0 0 25px blue, 0 0 5px darkblue;
}

CSS box-shadow Property


The CSS box-shadow property applies shadow to elements.
In its simplest use, you only specify the horizontal shadow and the vertical shadow:

Example:
div {
   box-shadow: 10px 10px;
}

CSS Shadow Properties

63
Exercises
1.

In the exercises for this chapter, you are going to continue to work on the Example Café web site:

a. First, open the index.html page and add a < div > element just inside the opening < body > tag and
the closing < /body > tag, and give the element an id attribute whose value is page. Repeat this for each
page of the site.

b. Now, in the style sheet add a rule that gives this element a margin, border, and padding so that it looks
like the border in Figure

< !DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”


“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

< html xmlns=”http://www.w3.org/1999/xhtml”>

< head > < title > Example Cafe - community cafe in Newquay, Cornwall, UK< /title > < link
rel=”stylesheet” type=”text/css” href=”css/interface.css” /> < meta http-equiv=”Content-Type”
content=”text/html; charset=iso-8859-1”/>

< /head >

< body >

< div id=”page” >

< a id=”top” > < img src=”images/logo.gif” alt=”example cafe” width=”194” height=”80” />

< div id=”navigation” > HOME < a href=”menu.html” > MENU < /a >

< a href=”recipes.html” > RECIPES < /a >

64
< a href=”opening.html” > OPENING < /a >

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

< /div >

< img src=”images/scrambled_eggs.jpg” width=”622” height=”370” alt=”Photo of scrambled eggs on an


English muffin” align=”left” />

< h2 > A community cafe serving home cooked, locally sourced, organic food < /h2 >

< p > With stunning views of the ocean, Example Cafe offers the perfect environment to unwind and
recharge the batteries.< /p >

< p > Our menu offers a wide range of breakfasts, brunches and lunches, including a range of vegetarian
options.< /p >

< p > Whether you sip on a fresh, hot coffee or a cooling smoothie, you never need to feel rushed - relax
with friends or just watch the world go by. < /p >

< h2 > This weekend’s special brunch < /h2 >

< p > This weekend, our season of special brunches continues with scrambled egg on an English muffin. Not
for the faint-hearted, the secret to these eggs is that they are made with half cream and cooked in butter,
with no more than four eggs in the pan at a time. < /p >

< /div >

< /body >

< /html >

Now here is the CSS rule that creates the blue border:

#page { width:960px; border:10px solid #3399cc; padding:40px; margin:20px;}

2. Create a CSS rule that will make the following changes to the navigation:

a. Add a single pixel gray border on the top and bottom.

b. Give it 20 pixels of margin above and below the gray lines.

c. Give it 10 pixels of padding on the top and bottom in the box.

d. Add a margin to the right of each link in the navigation.

The first three changes (for points a, b, and c) can be handled using one CSS rule. The rule will need to
control four properties:

The border - top and border - bottom properties add a single - pixel gray line above and below the
navigation The padding property adds space between the lines and the items in the navigation The
margin property adds a bit of space above and below the gray lines

65
Then the margin - right property can be used to add space to the right of each individual link.

#navigation { border-top: 1px solid #d6d6d6; border-bottom: 1px solid #d6d6d6; padding: 10px
0px 10px 0px; margin: 20px 0px 20px 0px ;} #navigation a { color:#3399cc; text-decoration:
none

3. Give the main image on the homepage a class attribute whose value is main_image, then create a rule
that gives the image a single - pixel black border, and also give the image a 10 - pixel margin on the right and
bottom sides of the image.

.main_image { border: 1px solid #000000; margin: 0px 10px 10px 0px ;}

4. Increase the gaps between each line of text to 1.3 em.

p{ color:#333333; font-size:90%; line-height:1.3em;}

66
Chapter (5)
JavaScript

1. You can access information from a document using the Document Object Model
2. To get information from a document, you can use JavaScript to perform calculations upon the data
in the document.

Introduction to JavaScript
5.1. What is JavaScript?
Javascript is a dynamic computer programming language. It is lightweight and most commonly used as a part
of web pages, whose implementations allow client-side script to interact with the user and make dynamic
pages. It is an interpreted programming language with object-oriented capabilities.
JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript, possibly because of
the excitement being generated by Java.
The general-purpose core of the language has been embedded in Netscape, Internet Explorer, and other
web browsers.
The defined a standard version of the core JavaScript language.
 JavaScript is a lightweight, interpreted programming language.
 Designed for creating network-centric applications.
 Complementary to and integrated with Java.
 Complementary to and integrated with HTML.
 Open and cross-platform

Client-side JavaScript
Client-side JavaScript is the most common form of the language. The script should be included in or
referenced by an HTML document for the code to be interpreted by the browser.
It means that a web page need not be a static HTML, but can include programs that interact with the user,
control the browser, and dynamically create HTML content.
The JavaScript client-side mechanism provides many advantages over traditional CGI server-side scripts.
The JavaScript code is executed when the user submits the form, and only if all the entries are valid, they
would be submitted to the Web Server.
JavaScript can be used to trap user-initiated events such as button clicks, link navigation, and other actions
that the user initiates explicitly or implicitly.

Advantages of JavaScript
 Less server interaction − you can validate user input before sending the page off to the server. This saves
server traffic, which means fewer loads on your server.

67
 Immediate feedback to the visitors − They don't have to wait for a page reload to see if they have
forgotten to enter something.
 Increased interactivity − you can create interfaces that react when the user hovers over them with a
mouse or activates them via the keyboard.
 Richer interfaces − you can use JavaScript to include such items as drag-and-drop components and
sliders to give a Rich Interface to your site visitors.

Limitations of JavaScript
We cannot treat JavaScript as a full-fledged programming language. It lacks the following important features.
 Client-side JavaScript does not allow the reading or writing of files. This has been kept for security
reason.
 JavaScript cannot be used for networking applications because there is no such support available.
 JavaScript doesn't have any multithreading or multiprocessor capabilities.
Once again, JavaScript is a lightweight, interpreted programming language that allows you to build
interactivity into otherwise static HTML pages.

JavaScript Development Tools


One of major strengths of JavaScript is that it does not require expensive development tools. You can start
with a simple text editor such as Notepad. Since it is an interpreted language inside the context of a web
browser, you don't even need to buy a compiler.
To make our life simpler, various vendors have come up with very nice JavaScript editing tools.
Some of them are listed here −
 Microsoft FrontPage − Microsoft has developed a popular HTML editor called FrontPage. FrontPage also
provides web developers with a number of JavaScript tools to assist in the creation of interactive
websites.
 Macromedia Dreamweaver MX − Macromedia Dreamweaver MX is a very popular HTML and JavaScript
editor in the professional web development crowd. It provides several handy prebuilt JavaScript
components, integrates well with databases, and conforms to new standards such as XHTML and XML.
 Macromedia HomeSite 5 − HomeSite 5 is a well-liked HTML and JavaScript editor from Macromedia that
can be used to manage personal websites effectively.

5.2. The Document Object Model

What is DOM?

JavaScript by itself doesn’t do much more than allow you to perform calculations or work with basic strings.
In order to make a document more interactive, the script needs to be able to access the contents of the
document and know when the user is interacting with it.

68
The script does this by interacting with the browser by using the properties, methods and events set out in
the interface called the Document Object Model.
The Document Object Model, or DOM, represents the web page that is loaded into the browser using a
series of objects.
The main object is the document object, which in turn contains several other child objects.
The DOM explains what properties of a document a script can retrieve and which ones it can alter; it also
defines some methods that can be called to perform an action on the document.

The W3C DOM standard is separated into 3 different parts:

 Core DOM - standard model for all document types


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

What is HTML DOM?

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

 The HTML elements as objects


 The properties of all HTML elements
 The methods to access all HTML elements
 The events for all HTML elements

In other words, the HTML DOM is a standard for how to get, change, add or delete HTML elements.

DOM nodes
According to the Dom, evening in an HTML document is a node. The DOM says:
 The entire document is a document node
 Every HTML element is an element node
 The text in the HTML elements are texts nodes
 Every HTML attributes is an attribute node
 Comments are comment nodes

DOM Example:

<html>
<head>
<title>DOM Exercise</title></head>
<body>
<h1>DOM Lesson One</h1>
<p>Hello Computech</p>
</body>
</html>
 The <html> node has two child nodes; <head> and <body>.
 The <head> node holds a <title> node. The <body> node holds a <h1> and <p> node.

69
 The HTML DOM model is constructed as a tree of Objects
 The HTML DOM views a HTML document as a tree structure. The tree structure is called a node-tree.

 With the HTML DOM, all nodes in the node tree can be accessed by JavaScript.
 New nodes can be created, and all nodes can be modified or deleted.

Node Relationships
The nodes in the node tree have a hierarchical relationship to each other.
The terms parent, child, and sibling are used to describe the relationships.
 In a node tree, the top node is called the root (or root node)
 Every node has exactly one parent, except the root (which has no parent)
 A node can have a number of children
 Siblings (brothers or sisters) are nodes with the same parent

<html>
<head>
<title>DOM Tutorial</title>
</head>
<body>
    <h1>DOM Lesson one</h1>
    <p>Hello world!</p>
</body>
</html>

The HTML DOM NodeList Object

A NodeList object is a list (collection) of nodes extracted from a document. A NodeList object is almost the
same as an HTMLCollection object.
Some (older) browsers return a NodeList obj ect instead of an HTMLCollection for methods like
getElementsByClassName().

70
 All browsers return a NodeList object for the property childNodes. 

 Most browsers return a NodeList object for the method querySelectorAll().

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


Example:

<p id="demo"></p>

<script>

var myNodelist = document.querySelectorAll("p");

The DOM Programming Interface

The HTML DOM can be accessed with JavaScript (and with other programming languages).
In the DOM, all HTML elements are defined as objects.
The programming interface is the properties and methods of each object.

HTML DOM Methods

HTML DOM properties are values (of HTML Elements) that you can set or change.
HTML DOM methods are actions you can perform (on HTML Elements).

A property is a value that you can get or set (like changing the content of an HTML element).

 innerHTML- Holds the HTML inside a set of HTML tags.

 nodeName- The name of an HTML element or element’s attribute.

 Id- The “id” attribute of an HTML element.

 parentNode -A reference to the node one level up in the DOM.

 childNodes- An array of references to the nodes one level down in the DOM.

 Attributes- An array of attributes of an HTML element.

 Style- An object encapsulating the CSS/HTML styling of an element.

A method is an action you can do (like add or deleting an HTML element).

 getElementById(id)- Gets the element with a given ID below this point in the DOM.
 getElementsByTagName(tag)-Gets all elements with the given tag below this point in the DOM.
 appendChild(node)-Add the given node to the DOM below this point.
 removeChild(node)-Remove the specified child node from the DOM.

71
Example:

<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>
</body>
The getElementById Method
</html>
The most common way to access an HTML element is to use the id of the element.
In the example above the getElementById method used id="demo" to find the element.

The innerHTML Property


The easiest way to get the content of an element is by using the innerHTML property.
The innerHTML property is useful for getting or replacing the content of HTML elements.
The innerHTML property can be used to get or change any HTML element, including <html> and <body>.

The HTML DOM Document Object

The document object represents your web page.


If you want to access any element in an HTML page, you always start with accessing the document object.
Below are some examples of how you can use the document object to access and manipulate HTML.

Finding HTML Elements


Method Description
document.getElementById(id) Find an element by element id
document.getElementsByTagName(name) Find elements by tag name
document.getElementsByClassName(name) Find elements by class name

Changing HTML Elements


Property Description

element.innerHTML =  new html content Change the inner HTML of an element


element.attribute = new value Change the attribute value of an HTML element
element.style.property = new style Change the style of an HTML element

Method Description
element.setAttribute(attribute, value) Change the attribute value of an HTML element
Adding and Deleting Elements
Description
Method

72
document.createElement(element) Create an HTML element

document.removeChild(element) Remove an HTML element

document.appendChild(element) Add an HTML element

document.replaceChild(new, old) Replace an HTML element

document.write(text) Write into the HTML output stream

5.3. Reacting to Events


A JavaScript can be executed when an event occurs, like when a user clicks on an HTML element.
To execute code when a user clicks on an element, add JavaScript code to an HTML event attribute:
onclick=JavaScript

Examples of HTML events:

 When a user clicks the mouse


 When a web page has loaded
 When an image has been loaded
 When the mouse moves over an element
 When an input field is changed
 When an HTML form is submitted
 When a user strokes a key

onclick The event occurs when the user clicks on an


element
ondblclick The event occurs when the user double-clicks
on an element
onerror The event occurs when an error occurs while
loading an external file
onfocus The event occurs when an element gets focus

onload The event occurs when an object has loaded

onunload The event occurs once a page has unloaded (for


<body>)
onkeydown The event occurs when the user is pressing a
key
onkeypress The event occurs when the user presses a key

onkeyup The event occurs when the user releases a key

onmousedown The event occurs when the user presses a


mouse button over an element
onmousemove The event occurs when the pointer is moving
while it is over an element
onmouseover The event occurs when the pointer is moved
onto an element, or onto one of its children
onmouseout The event occurs when a user moves the mouse
pointer out of an element, or out of one of its
children

73
onmouseup The event occurs when a user releases a mouse
button over an element
onmouseleave The event occurs when the pointer is moved
out of an element
onresize The event occurs when the document view is
resized
onselect The event occurs after the user selects
some text (for <input> and <textarea>)
onsubmit The event occurs when a form is submitted

5.4. JavaScript Syntax

JavaScript can be implemented using JavaScript statements that are placed within the <script>... </script>
HTML tags in a web page.
You can place the <script> tags, containing your JavaScript, anywhere within you web page, but it is normally
recommended that you should keep it within the <head> tags.
The <script> tag alerts the browser program to start interpreting all the text between these tags as a script. A
simple syntax of your JavaScript will appear as follows.

<script ...>
JavaScript code
</script>

The script tag takes two important attributes:


Language: This attribute specifies what scripting language you are using.
Typically, its value will be javascript. Although recent versions of HTML (and XHTML, its successor) have
phased out the use of this attribute.
Type: This attribute is what is now recommended to indicate the scripting language in use and its value
should be set to "text/javascript".
So your JavaScript syntax will look as follows.

<script language="javascript" type="text/javascript">


JavaScript code
</script>

Your First JavaScript Code

Let us take a sample example to print out "Hello World". We added an optional HTML comment that
surrounds our JavaScript code.
This is to save our code from a browser that does not support JavaScript.
The comment ends with a "//-- >".
Here "//" signifies a comment in JavaScript, so we add that to prevent a browser from reading the end of the
HTML comment as a piece of JavaScript code.

74
Next, we call a function document.write which writes a string into our HTML document.
This function can be used to write text, HTML, or both. Take a look at the following code.

<html>
<body>
<script language="javascript" type="text/javascript">
<!--
document.write ("Hello World!")
//-->
</script>
</body>
</html>
Comments in JavaScript
JavaScript supports both C-style and C++-style comments. Thus:
 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.
 JavaScript also recognizes the HTML comment opening sequence <!--. JavaScript treats this as a single-
line comment, just as it does the // comment.
 The HTML comment closing sequence --> is not recognized by JavaScript so it should be written as //-->.

The following example shows how to use comments in JavaScript.

<script language=”javascript” 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>

5.5. PLACEMENT

 Script in <head>...</head> section.


 Script in <body>...</body> section.
 Script in <body>...</body> and <head>...</head> sections.
 Script in an external file and then include in <head>...</head> section.

1. JavaScript in <head>...</head> Section


If you want to have a script run on some event, such as when a user clicks somewhere, then you will place
that script in the head as follows.

75
<html>
<head>
<script type=”text/javascript”>
<! - -
Function sayHello() {
Alert(“Hello world”)}
// - ->
</script></head>
<body>Click here for the result
<input type=”button” onclick=”sayHello()” value=”Say Hello”/>
2.</body></html>
JavaScript in <body>...</body> Section

If you need a script to run as the page loads so that the script generates content in the page, then the script
goes in the <body> portion of the document. In this case, you would not have any function defined using
JavaScript. Take a look at the following code.

<html>
<head></head>
<body>
<script type=”text/javascript”>
<! - -
Document.write (“Hello world”)
// - ->
</script>
<p> This is web page body </p>
</body></html>

3. JavaScript in <body> and <head> Sections


You can put your JavaScript code in <head> and <body> section altogether as follows .

<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body></html>
Script in External File
Here is an example to show how you can include an external JavaScript file in your HTML code using script
tag and its src attribute.

76
<html>
<head>
<script type="text/javascript" src="filename.js" ></script>
</head>
<body>
.......
</body>
</html>

To use JavaScript from an external file source, you need to write all your JavaScript source code in a simple
text file with the extension ".js" and then include that file as shown above.
For example, you can keep the following content in filename.js file and then you can use sayHello function
in your HTML file after including the filename.js file.

function sayHello()
{
alert("Hello World")
}

Variables

Like many other programming languages, JavaScript has variables. Variables can be thought of as named
containers. You can place 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 must declare it. Variables are declared with the var
keyword as follows.

<script type="text/javascript">
<!--
var money;
var name;
</script>
//-->
<script atype="text/javascript">
Storing value in a variable is called variable initialization. You can do variable initialization at the time of
variable creation or at a later point in time when you need that variable.
For instance, you might create variable named money and assign the value 2000.50 to it later.
For another variable, you can assign a value at the time of initialization as follows.

<script type="text/javascript">
<!--
var name = "Ali";
var money;
money = 2000.50;
//-->
</script> Variable Scope
JavaScript

The scope of a variable is the region of your program in which it is defined.


JavaScript variables have only two scopes.

77
 Global Variables: A global variable has global scope which means it can be defined anywhere in your
JavaScript code.
 Local Variables: A local variable will be visible only within a function where it is defined. Function
parameters are always local to that function.
Within the body of a function, a local variable takes precedence over a global variable with the same name.
If you declare a local variable or function parameter with the same name as a global variable, you effectively
hide the global variable. Take a look into the following example.

<script type="text/javascript">
<!--
var myVar = "global"; // Declare a global variable
function checkscope( ) {
var myVar = "local"; // Declare a local variable
document.write(myVar);
}
//-->
</script>

JavaScript Variable Names

While naming your variables in JavaScript, keep the following rules in mind.

 You should not use any of the JavaScript reserved keywords as a variable name. These keywords are
mentioned in the next section. For example, break or boolean variable names are not valid.
 JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or an
underscore character. For example, 123test is an invalid variable name but _123test is a valid one.
 JavaScript variable names are case-sensitive. For example, Name and name are two different variables.

5.6. OPERATORS
What is an Operator?

Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and ‘+’ is called the
operator. JavaScript supports the following types of operators.
 Arithmetic Operators
 Comparison Operators
 Logical (or Relational) Operators
 Assignment Operators
 Conditional (or ternary) Operators
Let’s have a look at all the operators one by one.

1. Arithmetic Operators

JavaScript supports the following arithmetic operators:


Assume variable A holds 10 and variable B holds 20, then:

78
2. Comparison Operators

JavaScript supports the following comparison operators:


Assume variable A holds 10 and variable B holds 20, then:

79
3. Logical Operators
JavaScript supports the following logical operators:

3.1 Bitwise Operators


JavaScript supports the following bitwise operators:

80
4. Assignment Operators
JavaScript supports the following assignment operators:

81
5. Conditional Operator (? :)

The conditional operator first evaluates an expression for a true or false value and then executes one of the
two given statements depending upon the result of the evaluation.

5.7. FUNCTIONS

A function is a group of reusable code which can be called anywhere in your program. This eliminates the
need of writing the same code again and again. It helps programmers in writing modular codes. Functions
allow a programmer to divide a big program into a number of small and manageable functions.
Like any other advanced programming language, JavaScript also supports all the features necessary to write
modular code using functions. You must have seen functions like alert() and write() in the earlier chapters.
We were using these functions again and again, but they had been written in core JavaScript only once.
JavaScript allows us to write our own functions as well.

Function Definition

Before we use a function, we need to define it. The most common way to define a function in JavaScript is by
using the function keyword, followed by a unique function name, a list of parameters (that might be empty),
and a statement block surrounded by curly braces.

Syntax

The basic syntax is shown here.

<script type="text/javascript">
<! - -
function functionname(parameter-list)
{
statements
}
//- ->
</script>

Example:

<script type="text/javascript">
<!- -
function sayHello()
{
Alert(“Hello there”);
}
//- ->
</script>

82
Calling a Function
To invoke a function somewhere later in the script, you would simply need to write the name of that
function as shown in the following code.

<html>
<head>
<script type="text/javascript">
function sayHello()
{
Document.write (“Hello there!”);
}
</script>
</head>
<body>
<p>
Click the following button to call the function</p>
<form>
<input type=”button” onclick=”sayHello()” value=”Say Hello”>
</form>
<p> Use different text in write method and then try….</p>
</body>
</html>

Function Parameters

Till now, we have seen functions without parameters. But there is a facility to pass different parameters
while calling a function. These passed parameters can be captured inside the function and any manipulation
can be done over those parameters. A function can take multiple parameters separated by comma.

Example:

Try the following example. We have modified our sayHello function here. Now it takes two parameters.

<html>
<head>
<script type="text/javascript">
function sayHello(name, age)
{
Document.write (name + “is” + age + “years old.”);
}
</script>
</head>
<body>
<p>
Click the following button to call the function</p>
<form>
<input type=”button” onclick=”sayHello(‘Zara’ ,7)” value=”Say Hello”>
</form>
<p> Use different parmeters inside the function and then try..</p>
</body>
</html>

83
The return Statement

A JavaScript function can have an optional return statement. This is required if you want to return a value
from a function. This statement should be the last statement in a function.

Example
It defines a function that takes two parameters and concatenates them before returning the resultant in the
calling program.

<html>
<head>
<script type="text/javascript">
function concatenate(first, last)
{
var full;
Full= first+ last;
Return full;
}
Function secondFunction()
{
var result;
Result = concatenate (‘Zara’ , ‘Ali’)
Document.write (result);
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type=”button” onclick=”secondFunction()” value=”Call Function”>
</form>
<p> Use different parameters inside the function and then try….</p>
</body>
</html>

5.8. Conditional Statements

JavaScript also contains a conditional operator that assigns a value to a variable based on some condition.

1. IF-ELSE statments

JavaScript supports conditional statements which are used to perform different actions based on different
conditions. JavaScript supports the following forms of if..else statement:
 if statement
 if...else statement
 if...else if... statement

1.1. if Statement

The ‘if’ statement is the fundamental control statement that allows JavaScript to make decisions and
execute statements conditionally.

84
Syntax
The syntax for a basic if statement is as follows:
If (expression) {
Statement (s) to be executed if expression is true }
1.2. if...else Statement

The ‘if...else’ statement is the next form of control statement that allows JavaScript to execute statements in
a more controlled way.

Syntax
The syntax of an if-else statement is as follows:

If (expression) {
Statement (s) to be executed if expression is true
}else{
Statement (s) to be executed if expression is false }

1.3.if...else if... Statement

The ‘if...else if...’ statement is an advanced form of if…else that allows JavaScript to make a correct decision
out of several conditions.

Syntax
The syntax of an if-else-if statement is as follows:

If (expression 1) {
Statement (s) to be executed if expression 1 is true
} else if (expression 2) {
Statement (s) to be executed if expression 2 is true
} else if (expression 3) {
Statement (s) to be executed if expression 3 is true
} else {
Statement (s) to be executed if no expression is true}
Example:
<html>
<body>
<script type=”text/javascript”> </script>
<! - - <p> Set the variable to different
var book = “maths” ; value and then try…</p>
If ( book == “history”) { </body>
Document.write(“<b>History book</b>”); </html>
} else if (book == “maths”) {
Document.write(“<b>Maths book</b>”);
} else if (book == “economics”) {
Document.write(“<b>Economics book</b>”);
} else {
Document.write(“<b>Unknown book</b>”);
}
2.// SWITCH-CASE
- -> statement

85
You can use multiple if...else…if statements, as in the previous chapter, to perform a multiway branch.
However, this is not always the best solution, especially when all of the branches depend on the value of a
single variable.

Syntax

Switch (expression)
{
Case condition 1: statement(s)
Break;
Case condition 2: statement(s)
Break;
…….
Case condition n: statement(s)
Break;
Default: statement(s)
}
Example:

<html>
<body>
<script type="text/javascript">
<!--
var grade='A';
document.write("Entering switch block<br />");
switch (grade)
{
case 'A': document.write("Good job<br />");
break;
case 'B': document.write("Pretty good<br />");
break;
case 'C': document.write("Passed<br />");
break;
case 'D': document.write("Not so good<br />");
break;
case 'F': document.write("Failed<br />");
break;
default: document.write("Unknown grade<br />")
}
document.write("Exiting switch block");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>

3. Looping Statement

86
While writing a program, you may encounter a situation where you need to perform an action over and over
again. In such situations, you would need to write loop statements to reduce the number of lines.
JavaScript supports all the necessary loops to ease down the pressure of programming.
There are two different kinds of loops:
 While –loops through a block of code while a specified condition is true
 For- loops through a block of code a specified number of times

The while Loop

The purpose of a while loop is to execute a statement or code block repeatedly as long as an expression is
true. Once the expression becomes false, the loop terminates.

Syntax

while (expression)
{
Statement(s) to be executed if expression is true
}

The do...while Loop

The do...while loop is similar to the while loop except that the condition check happens at the end of the
loop. This means that the loop will always be executed at least once, even if the condition is false.

Syntax

Do
{
Statement(s) to be executed;
}
while (expression);

The for Loop

The ‘for’ loop is the most compact form of looping. It includes the following three important parts:
 The loop initialization where we initialize our counter to a starting value. The initialization statement is
executed before the loop begins.
 The test statement which will test if a given condition is true or not. If the condition is true, then the
code given inside the loop will be executed, otherwise the control will come out of the loop.
 The iteration statement where you can increase or decrease your counter.

You can put all the three parts in a single line separated by semicolons.

Syntax

for (initialization; test condition; iteration statement){


Statement(s) to be executed if test condition is true
}
5.9. EVENTS

87
What is an Event?

JavaScript's interaction with HTML is handled through events that occur when the user or the browser
manipulates a page.
When the page loads, it is called an event. When the user clicks a button, that click too is an event. Other
examples include events like pressing any key, closing a window, resizing a window, etc.
Developers can use these events to execute JavaScript coded responses, which cause buttons to close
windows, messages to be displayed to users, data to be validated, and virtually any other type of response
imaginable.
Events are a part of the Document Object Model (DOM) Level 3 and every HTML element contains a set of
events which can trigger JavaScript Code.

onclick Event Type


This is the most frequently used event type which occurs when a user clicks the left button of his mouse. You
can put your validation, warning etc., against this event type.
Example

<html>
<head>
<script type=”text/javascript”>
<! - -
Function sayHello() {
Document.write(“Hello World”);
}
// - ->
</script>
</head>
<body>
<p> Click the following button and see result</p>
<input type=”button” onclick=”sayHello()” value=”Say Hello”/>
</body>
</html>

onsubmit Event Type

onsubmit is an event that occurs when you try to submit a form. You can put your form validation against
this event type.

Example

88
<html>
<head>
<script type=”text/javascript”>
<! - -
Function validation() {
All validation goes here
........
Return either true or false
}
// - ->
</script>
</head>
<body>
<form method=”POST” action=”t.cgi” onsubmit=”return validate()”>
..... .... .
<input type=”submit” value=”Submit”/>
</form>
</body>
</html>

onmouseover and onmouseout


These two event types will help you create nice effects with images or even with text as well.
The onmouseover event triggers when you bring your mouse over any element and the onmouseout
triggers when you move your mouse out from that element.

Example

<html>
<head>
<script type=”text/javascript”>
<! - -
Function over() {
Document.write (“Mouse over”);
}
Function out() {
Document.write (“Mouse out”);
}
// - ->
</script>
</head>
<body>
<p>Bring your mouse inside the division to see the result:</p>
<div onmouseover = “over()” onmouseout=”out()”>
<h2> This is inside the division </h2>
</div>
</body>
</html>
5.10. DIALOG BOX

89
JavaScript supports three important types of dialog boxes. These dialog boxes can be used to raise and alert,
or to get confirmation on any input or to have a kind of input from the users. Here we will discuss each
dialog box one by one.

1. Alert Dialog Box


An alert dialog box is mostly used to give a warning message to the users.
For example, if one input field requires entering some text but the user does not provide any input, then as a
part of validation, you can use an alert box to give a warning message.
Nonetheless, an alert box can still be used for friendlier messages. Alert box gives only one button "OK" to
select and proceed.

Example

<html>
<head>
<script type=”text/javascript”>
<! - -
Function Warn() {
Alert (“This is a warning message!”);
Document.write (“This is a warning message!”);
}
// - ->
</script>
</head>
<body>
<p>Click the following button to see the result:</p>
<form>
<input type= “button” value=”Click me” onClick=”Warn();”/>
</form>
</body>
</html>

2. Confirmation Dialog Box


A confirmation dialog box is mostly used to take user's consent on any option. It displays a dialog box with
two buttons: OK and Cancel.
If the user clicks on the OK button, the window method confirm() will return true. If the user clicks on the
Cancel button, then confirm() returns false. You can use a confirmation dialog box as follows.
Example:

<html>
<head>
<script type=”text/javascript”>
<! - -
Function getConfirmation() {
var retVal = confirm(“Do you want to continue?”);
If (retVal = = true ){
Document.write (“User want to continue!”);
return true;
90
}else{
document.write (“User does not want to continue!”);
return false;
}
}
// - ->
</script>
</head>
<body>
<p>Click the following button to see the result:</p>
<form>
<input type= “button” value=”Click me” onClick=”getConfirmation();”/>
</form>
</body>
</html>

3. Prompt Dialog Box

The prompt dialog box is very useful when you want to pop-up a text box to get user input. Thus, it enables
you to interact with the user. The user needs to fill in the field and then click OK.
This dialog box is displayed using a method called prompt() which takes two parameters:
(i) a label which you want to display in the text box and
(ii) (ii) a default string to display in the text box.
This dialog box has two buttons: OK and Cancel. If the user clicks the OK button, the window method
prompt() will return the entered value from the text box. If the user clicks the Cancel button, the window
method prompt() returns null.

Example:

<html>
<head>
<script type=”text/javascript”>
<! - -
Function getValue() {
var retVal = prompt(“Enter your name :” , “your name here”);
Document.write (“You have entered : ” + retVal );
}
// - ->
</script>
</head>
<body>
<p>Click the following button to see the result:</p>
<form>
<input type= “button” value=”Click me” onClick=” getValue();”/>
</form>
</body>
</html>

91
Output

The “echo“ or “print” equivalent in JavaScript can be achieved by instructing it to place the text you want
into the DOM (Document Object Model). We reference the document object in JavaScript with the word
document, and call the write method to produce our output:
<script language="javascript">
document.write ("Some output from <b>JavaScript!</b>");
</script>

We can be more specific as to the exact place(s) on the page we wish to put our content. In PHP, we
would simply place our print or echo statement where we want the content to appear. With JavaScript we
can continue to take advantage of the document object model to specify where we want output to be. This
also means the script that makes the content can be stored in a separate location from the output location
itself:
<script language="javascript">
document.getElementById("ourText").innerHTML ="Hello World";
</script>
<div id="ourText"></div>

This is the basic approach taken when we use JavaScript to make changes to our page.

5.11. Build in Objects

You learned about the document object at the beginning of the chapter and now it is time to see some of
the objects that are built into the JavaScript language. You will see the methods that allow you to perform
actions upon data, and properties that tell you something about the data.

1. Strings

The string object allows you to deal with strings of text. Before you can use a built - in object, you need to
create an instance of that object.

You create an instance of the string object by assigning it to a variable like so:

myString = new String(‘Here is some bold text’)

The string object now contains the words “Here is some bold text” and this is stored in a variable called

myString. Once you have this object in a variable, you can write the string to the document or perform
actions upon it.

For example, the following method writes the string as if it were in a < b > element:

document.write(myString.bold())

92
You can check the length of this string like so; the result will be the number of characters including spaces
and punctuation:

MyString = new String(“How many characters are in this sentence?”) alert(myString.length)

Before you can use the string object, remember you first have to create it and then give it a value.

Properties

The following table shows the main property for the string object and its purpose.

Property Purpose

length Returns the number of characters in a string.

Example:

<html>
<body>
<script type=”text/javascript”>
var txt=”Hello!!!Greeting a head”;
Document.write(txt.length);
</script>
</body>
</html>

Methods

The following table lists the methods for the string object and their purposes.

Method Purpose

anchor(name) Creates an anchor element (an < a > element with a name or id
attribute rather than a href attribute).

big() Displays text as if in a < big > element.

bold() Displays text as if in a < bold > element.

charAt(index) Returns the character at a specified position (for example, if you have a
string that says “ banana ” and your method reads charAt(2) , then you
will end up with the letter n — remember that indexes start at 0).

fixed() Displays text as if in a < tt > element.

fontcolor(color) Displays text as if in a < font > element with a color attribute.

fontsize(fontsize) Displays text as if in a < font > element with a size attribute.

93
lastIndexOf(searchValue Same as indexOf() method, but runs from right to left.
, [fromIndex])

link(targetURL) Creates a link in the document.

small() Displays text as if in a < small > element.

strike() Displays text as if in a < strike > element.

sub() Displays text as if in a < sub > element.

substr(start, [length]) Returns the specified characters. 14,7 returns 7 characters, from the 14
th character (starts at 0).

substring(startPosition, Returns the specified characters between the start and end index points.
endPosition) 7,14 returns all characters from the 7th up to but not including the 14th
(starts at 0).

sup() Displays text as if in a < sup > element.

toLowerCase() Converts a string to lowercase.

toUpperCase() Converts a string to uppercase.

2. Date
The date object helps you work with dates and times. You create a new date object using the date
constructor like so:
new Date()
You can create a date object set to a specific date or time, in which case you need to pass it one of four
parameters:

 milliseconds : This value should be the number of milliseconds since 01/01/1970.


 dateString : Can be any date in a format recognized by the parse() method.
 yr_num , mo_num , day_num : Represents year, month, and day.
 yr_num , mo_num , day_num , hr_num , min_num , seconds_num , ms_num : Represents the years,
days, hours, minutes, seconds, and milliseconds.

Examples:
var birthDate = new Date(8298400000) document.write(birthDate)
var birthDate = new Date(“April 16, 1975”) document.write(birthDate)
var birthDate = new Date(1975, 4, 28) document.write(birthDate)

94
The following table shows some commonly used methods of the date object.

Method Purpose

date() Returns a Date object


getDate() Returns the date of a Date object (from 1 to 31)
getDay () Returns the day of a Date object (from 0 to 6;
0=Sunday, 1=Monday, and so on)
getMonth () Returns the month of a Date object (from 0 to
11; 0=January, 1=February, and so on)
getFullYear () Returns the year of a Date object (four digits)
getYear() R eturns the year of a Date object using only two
digits (from 0 to 99)
getHours() Returns the hours of a Date object (from 0 to 23)
getMinutes() Returns the minutes of a Date object (from 0 to 59)
getSeconds() Returns the seconds of a Date object (from 0 to 59)
getTime() Returns the number of milliseconds since midnight
1/1/1970

3. Math

The math object helps in working with numbers. It has properties for mathematical constants and methods
representing mathematical functions such as the Tangent and Sine functions.

numberPI = Math.PI document.write (numberPI)

The following example rounds pi to the nearest whole number (integer) and writes it to the screen
numberPI = Math.PI numberPI = Math.round(numberPI) document.write (numberPI)

4. Arrays

Create an array, assign values to it, and write the values to the output. An array is a special variable, which
can hold more than one value, at a time. An array can be defined in three ways.
Arrays in JavaScript work in much the same way as PHP. All we need to keep in mind is that our output needs
to use DOM manipulation:
4.1 Regular array

var x;
var mycars = new Array();
mycars[0] = “Saab”;
mycars[1] = “Volvo”; 95
mycars[2] = “BMW”;
for (x=0; x<stooges.length; x++){
4.2 Condensed array
var car=new array(‘’Saab”, “Volvo”, “BMW”);

4.3 Literal array

var car=[‘’Saab”, “Volvo”, “BMW”];

An example of the toString() method, which converts the array to a string.


document.write(‘These are ‘ + car.toString())

Methods

The table that follows lists the methods of an array:

Method Purpose
concat() Joins (or concatenates) two or more arrays to create one new one
Joins all of the elements of an array together separated by the character
join(separator) specified as a separator (the default is a comma)
reverse() Returns the array with items in reverse order
slice() Returns a selected part of the array (if you do not need it all)
sort() Returns a sorted array, sorted by alphabetical or numerical order

5.12. Table Object

The Table object represents an HTML <table> element.

Access a Table Object

You can access a <table> element by using getElementById():

Example: var x = document.getElementById("myTable");

<!DOCTYPE html>
<html>
<head><style>
table, td {
border: 1px solid black;}
</style>
</head>
<body>
<h3>A demonstration of how to access a TABLE element</h3>

96
<table id="myTable">
<tr>

<td>cell 1</td>
<td>cell 2</td>
</tr>
<tr>
<td>cell 3</td>
<td>cell 4</td>
</tr>
</table>
<p>Click the button to remove the first row in the table.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var x = document.getElementById("myTable");
x.deleteRow(0);
}
</script>
</body>
</html>

Create a Table Object


You can create a <table> element by using the document.createElement() method:
Example: var x = document.createElement("TABLE");

<!DOCTYPE html>
<html>
<head>
<style>
table, td {
border: 1px solid black;
}
</style>
</head>
<body>
<p>Click the button to create a TABLE, a TR and a TD element.</p>
<button onclick="myFunction()">Try it</button>

97
<script>

function myFunction() {
var x = document.createElement("TABLE");
x.setAttribute("id", "myTable");
document.body.appendChild(x);
var y = document.createElement("TR");
y.setAttribute("id", "myTr");
document.getElementById("myTable").appendChild(y);
var z = document.createElement("TD");
var t = document.createTextNode("cell");
z.appendChild(t);
document.getElementById("myTr").appendChild(z);
}
</script>
</body>
</html>

Table Object Properties

98
Table Object Methods

5.13. The <form> Element

The HTML <form> element defines a form that is used to collect user input:

99
<form>
.
form elements
.
</form>

An HTML form contains form elements.

Example:

<!DOCTYPE html>
<html>
<body>
<h2>HTML Forms</h2>
<form action="/action_page.php">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<input type="submit" value="Submit">
</form>
<p>If you click the "Submit" button, the form-data will be sent to a page called
"/action_page.php".</p>
</body>
</html>

Form elements are different types of input elements, like text fields, checkboxes, radio buttons, submit
buttons, and more.

The <input> Element

The <input> element is the most important form element.


The <input> element can be displayed in several ways, depending on the type attribute.
Here are some examples:

<!DOCTYPE html>
<html>
<body>
<h2>Text Input</h2>
<form>
First name:<br> 100
<input type="text" name="firstname">
<br>
Last name:<br>
<input type="text" name="lastname">
Text Input

<input type="text">
<!DOCTYPE html> defines a one-line input field for text input:
</form>
Example:
<html>
<p>Note that the form itself is not
<body> visible.</p>

<h2>Text Input</h2> <p>Also note that the default width of a text


input field is 20 characters.</p>
<form>
</body></html>
First name:<br>

Radio Button Input

<input type="radio"> defines a radio button.


Radio buttons let a user select ONE of a limited number of choices:

Example:

<!DOCTYPE html>
<html>
<body>
<h2>Radio Buttons</h2>
<form>
<input type="radio" name="gender" value="male" checked> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other
</form>
</body>
</html>

The Submit Button


<input type="submit"> defines a button for submitting the form data to a form-handler.
The form-handler is typically a server page with a script for processing input data.
The form-handler is specified in the form's action attribute:
Example:

101
<!DOCTYPE html> <input type="text" name="lastname"
<html> value="Mouse"> <br><br>

<body> <input type="submit"


value="Submit">
<h2>HTML Forms</h2>
</form>
<form action="/action_page.php"> First name:<br>
<p>If you click the "Submit" button,
<input type="text" name="firstname" value="Mickey">
the form-data will be sent to a page
<br> called "/action_page.php".</p>
Last name:<br> </body>
</html>

Exercises

1. Create a script to write out the multiplication table for the number 5 from 1 to 20 using a while loop.
2. Modify you could the using the following script. This statement can say one of three things:

< script type=”text/JavaScript” >


date = new Date(); time = date.getHours();
if (time < 12) { document.write(‘Good Morning’);
}
 “<Good
/script >
Morning ” to visitors coming to the page before 12 P.M. (using an if statement).
 “ Good Afternoon ” to visitors coming to the page between 12 and 6 P.M. — again using an
 if statement. (Hint: You might need to use a logical operator.)
 “ Good Evening ” to visitors coming to the page after 6 P.M. up until midnight (again using an if
statement).
Exercise 1 Create a script to write out the multiplication table for the number 5 from 1 to 20 using a while
loop.

Answer:

The exercise is based around a counter (to work out where you are in your tables); each time the code is run,
the counter increments by 1. So, you need to make sure the counter can go up to 20, rather than 10. This
goes in the condition of the while loop:

while (i < 21) {

Then you need to change the multiplier, which is both written out and used in the calculation:

document.write(i + “ x 5 = “ + (i * 5) + “< br / > ” );

The final code should look like this:

< script type=”text/JavaScript” >

i = 1 while (i < 21) {

document.write(i + “ x 5 = “ + (i * 5) + “< br / > ” );

i ++

102
}

< /script >

Exercise 2

Modify ch11_eg06.html so that it can say one of three things:

- “ Good Morning ” to visitors coming to the page before 12 p.m. (using an if statement).

- “ Good Afternoon ” to visitors coming to the page between 12 and 6 p.m., again using an if statement.
(Hint: You might need to use a logical operator.)

-“ Good Evening ” to visitors coming to the page after 6 p.m. up until midnight (again using an if
statement).

Answer: This script needs to use the getHours() method of the date object to determine the time and then
uses if statements to check the appropriate time for each statement presented to the user.

Note how the afternoon uses a logical operator to check that it is after 12 but before 6 p.m.

< script type=”text/JavaScript” > date = new Date(); time = date.getHours();

if (time < 12) document.write(‘Good Morning’);


if (time > = 12 & & time < 18) document.write(‘Good Afternoon’)
if (time > = 18) document.write(‘Good Evening’);

< /script >

103

You might also like