Chapter (1) Fundamental of Web Technology
Chapter (1) Fundamental of Web Technology
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:
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:
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.
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
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:
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.
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)
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.
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
5
Chapter (2)
Fundamental of 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.
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
Introduction to 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.
Prerequisites: You will need a text editor, such as Notepad and an Internet browser, such as Internet
Explorer or Netscape.
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.
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?
<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.
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.
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:
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 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.
<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:
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.
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:
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>
HTML automatically adds an extra blank line before and after a heading. A useful heading attribute is align.
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.
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 <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:
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!
<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.
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.
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:
The most common character entity in HTML is the non-breaking space . 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 character entity.
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
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.
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:
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!
<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>
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
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).
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
<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>
HTML uses the <a> anchor tag to create a link to another document or web page.
An anchor can point to any resource on the Web: an HTML page, an image, a sound file, a movie, etc.
syntax:
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.
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:
Email Links
To create an email link, you will use mailto: plus your email address. Here is a link to ACC's Help Desk:
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:
To link directly to the top section, add a # sign and the name of the anchor to the end of a URL, like this:
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 is used to define an alternate text for an image. The value of the alt attribute is author-
defined text:
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:
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.
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> <img src="http://profdevtrain.austincc.edu/html/graphics/chef.gif"> </td>
</tr>
</table>
Headings in a Table
Headings in a table are defined with the <th> tag.
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.
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
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.
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>
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”>.
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.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.
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.
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.
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>
27
Exercises
It’s time to create your own page. Use your text editor to create a page which contains the following:
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
< div > HOME < a href=”menu.html” > MENU < /a > < a href=”recipes.html” > RECIPES < /a >
< a href=”contact.html” > CONTACT < /a > < /div >
< div > < a href=”index.html” > HOME < /a > MENU < a href=”recipes.html” > RECIPES < /a >
< a href=”contact.html” > CONTACT < /a > < /div >
< div > < a href=”index.html” > HOME < /a > < a href=”menu.html” > MENU < /a > RECIPES
< a href=”contact.html” > CONTACT < /a > < /div >
< 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
< head > < title > Reply to ad < /title > < /head >
< p > Use the following form to respond to the ad:< /p >
< 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 >
< td > < label for=”emailFrom” > To < /label > < /td >
< td > < input type=”text” name=”txtFrom” id=”emailFrom” size=”20” /> < /td >
< tr >
< td > < label for=”emailSubject” > Subject < /label > < /td >
< td > < input type=”text” name=”txtSubject” id=”emailSubject” size=”50” / > < /td >
< tr >
< td > < label for=”emailBody” > Body < /label > < /td >
< td > < textarea name=”txtBody” id=”emailBody” cols=”50” rows=”10”>< /textarea > </td >
32
Chapter (4)
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.
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
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;
}
/*element selection*/
h3{color: blue;
}
/*class selection*/
.c_head{
font-family: cursive;
color: orange;
}
/*id selection*/
#i_head{
font-variant: small-caps;
Color: red;
}
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>
36
4.2. CSS Styling
CSS background properties are used to define the background effects of an element.
• background-color
• background-image
• background-repeat
• background-attachment
• background-position
Background Color
Example:
body {background-color:#b0c4de;}
The background color can be specified by:
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
Example:
body {background-image:url('paper.gif');}
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; }
When using a background image, use an image that does not disturb the text.
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.
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.
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:
38
background-attachment: fixed
The background image will be fixed and will not move when the body is scrolled:
background-attachment: local
The background image of the div will scroll when the contents of the div is scrolled.
Background-position
The background-position property is used to specify the starting position for a background image or gradient
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
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).
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:
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 mostly used to remove underlines from links for design purposes:
Example:
a {text-decoration:none;}
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:
42
4.2.2. CSS Font
CSS font properties define the font family, boldness, size, and the style of a text.
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 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:
Font Style
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:
44
Absolute size is useful when the physical size of the output is known
Relative size:
If you do not specify a font size, the default size for normal text, like paragraphs, is 16px (16px=1em).
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.
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:
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:
When setting the style for several link states, there are some order rules:
Text Decoration
Example:
a:link {text-decoration:none;}
a:visited {text-decoration:none;}
a:hover {text-decoration:underline;}
a:active {text-decoration:underline;}
Background Color
Example:
a:link {background-color:#B2FF99;}
a:visited {background-color:#FFFF85;}
a:hover {background-color:#FF704D;}
a:active {background-color:#FF704D;}
With CSS, lists can be styled further, and images can be used as the list item marker.
The type of list item marker is specified with the list-style-type property:
47
Example:
ul.a {list-style-type: circle;}
Some of the property values are for unordered lists, and some for ordered lists.
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
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;
}
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
Table Borders
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; }
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 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; }
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;
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
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; }
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.
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.
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;
56
This example demonstrates how to set the bottom margin of a text using a percent value.
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
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.
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
62
box-shadow
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;
}
Example:
div {
box-shadow: 10px 10px;
}
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
< 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”/>
< 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 >
64
< a href=”opening.html” > OPENING < /a >
< 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 >
< 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 >
Now here is the CSS rule that creates the blue border:
2. Create a CSS rule that will make the following changes to 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 ;}
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.
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 HTML DOM is a standard object model and programming interface for HTML. It defines:
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>
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.
<p id="demo"></p>
<script>
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 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).
childNodes- An array of references to the nodes one level down in the DOM.
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.
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
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
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>
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 //-->.
5.5. PLACEMENT
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>
<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
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>
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
78
2. Comparison Operators
79
3. Logical Operators
JavaScript supports the following logical 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
<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>
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 }
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 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 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 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
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.
<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 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>
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.
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>
<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>
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.
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:
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:
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
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).
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).
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])
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).
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:
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
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.
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”);
Methods
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
<!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>
<!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>
98
Table Object Methods
The HTML <form> element defines a form that is used to collect user input:
99
<form>
.
form elements
.
</form>
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.
<!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>
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>
101
<!DOCTYPE html> <input type="text" name="lastname"
<html> value="Mouse"> <br><br>
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:
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:
Then you need to change the multiplier, which is both written out and used in the calculation:
i ++
102
}
Exercise 2
- “ 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.
103